/*
 * 结果显示
 **/
Core.FileResultDG = (function(){
    var _model;
    return {
        Show: function(list, win){
            if(!_model){
                 
                var _content = $('<div class="copy-list"><dl class="file-list" rel="con"></dl></div>'+
                        '<div class="dialog-bottom">'+
                            '<div class="fr"><a href="javascript:;" class="button" btn="cancel">关 闭</a></div>' +
                        '</div>');
                _model = new Core.DialogBase({
                    title: '结果', 
                    content: _content
                });
            }
            _model.Open(function(){
                _model.warp.find("[btn='close_btn']").click(function(){
                    _model.Close();
                    return false;
                })
				
                var html = [];
                for(var k in list){
                    var item = list[k];
                    var fileName = item["file_name"];
                    var icotype = item["ico"];
                    var result = item.state? '<i class="icon ico-done"></i>' : item.msg;
                    html.push('<dd ' + (!item.state? 'class="err" title="' + item.msg + '"' : "") + '><ul><li class="file-name"><i class="file-type"></i>' + fileName + '</li><li class="file-rate">' + result + '</li></ul></dd>')
                }
                _model.warp.find("[rel='con']").html('<dt><ul><li class="file-name">文件名</li><li class="file-rate">操作结果</li></ul></dt>' + html.join(""));
            },win);
        }
    }
})();

/*目录选择对话框*/
Core.TreeDG = (function(){
    var _TreeSelect = function(){
        var _self = this, _cache = {};
        
        var _content = $('<div class="file-copy">'+
                            '<div class="directory-tree" rel="tree"></div>'+
                        '</div>' + 
                        '<div class="dialog-bottom">'+
                            '<div class="fl"><a href="javascript:;" class="button btn-green" btn="add_folder">新建文件夹</a></div>'+
                            '<div class="fr">'+
                                
                                '<a href="javascript:;" class="button" btn="confirm">确 定</a>'+
                                '<a href="javascript:;" class="button btn-gray" btn="cancel">取 消</a></div>'+
                            '<div class="fr" rel="is_copy_box">'+
                                '<input type="checkbox" rel="is_copy" id="js_treedg_is_copy_cb" style="vertical-align:middle;">'+
                                '<label for="js_treedg_is_copy_cb" style="display:inline-block;line-height:30px;vertical-align:middle;color:#15A2F8">保留原件</label>'+
                            '</div>'+
                        '</div>');
        Core.DialogBase.call(this,{
            title: '请选择目录', 
            content: _content
        });	//继承 dialog
		
        this.Initial = function(){
            var tree_box = _content.find("[rel='tree']");
            tree_box.html("");
            var treeData = Core.Tree.GetTree(20);
            if(treeData){
                var ul = $("<dl></dl>");
                for(var k in treeData){
                    treeData[k].find("[aid='0']").parent().empty().remove();
                    treeData[k].find("[aid='5']").parent().empty().remove();
                    ul.append(treeData[k].clone(true));
                }
                tree_box.append(ul);
                ul.find("a[cid]").click(function(){
                    var ele = $(this);
                    var aid = ele.attr("aid");
                    var cid = ele.attr("cid");
					
                    var isOpen = !(ele.find("i[rel='open']").hasClass("ino") && ele.hasClass("focus"))
                    
                    ul.find("a.focus").removeClass("focus");
                    if(isOpen){
                        Core.Tree.OpenChild(cid,[ul]);
                    }
                    else{
                        Core.Tree.HideChild(cid,[ul]);
                    }
					
                    $(this).addClass("focus");
                    _cache.aid = aid;
                    _cache.cid = cid;
                    Util.Cookie.set("select_tree_node_old_cid", _cache.cid.toString());
                    return false;
                });
                var defaultCid = Util.Cookie.get("select_tree_node_old_cid");
                
                if(!defaultCid) {defaultCid = "1_0";}
                
                var a = ul.find("[cid='"+defaultCid+"']");
                if(a.length){
                    window.setTimeout(function(){
                        a.click();
                    },10);
                }
                
            }
            _cache.aid = false;
            _cache.cid = false;
            _content.find("[btn]").unbind("click").bind("click",function(){
                switch($(this).attr("btn")){
                    case "add_folder":
                        if(!checkSelectDir()) return;
                        
                        Core.Tree.AddNode(_content.find("[rel='tree']").find("a.focus").parent(), tree_box, function(newCid){
                            var aEle = tree_box.find("a[cid='"+newCid+"']");
                            aEle.click(function(){
                                var aid = $(this).attr("aid");
                                var cid = $(this).attr("cid");
								
                                ul.find("a.focus").removeClass("focus");
                                Core.Tree.OpenChild(cid,[ul]);
								
                                $(this).addClass("focus");
                                _cache.aid = aid;
                                _cache.cid = cid;
                                return false;
                            })
                            aEle.click();
                        }, true);
                        break;
                    case "confirm":
                        if(!checkSelectDir()) return;
                        
                        
                        switch(_cache.op_type){
                            case "move":
                                confirmFun();
                                break;
                            case "copy":
                                confirmFun();
                                break;
                            case "move_folder":
                                //转移文件夹
                                moveFolderfun();
                                break;
                        }
                        break;
                    case "cancel":
                        _self.Close();
                        break;
                }
                return false;
            })
        }
		
        var checkSelectDir = function(){
            if(_cache.aid === false){
                Core.MinMessage.Show({
                    text: "请选择目录", 
                    timeout: Core.CONFIG.MsgTimeout, 
                    type:"war", 
                    window: _self
                });
                return false;
            }
            return true;
        }
		
        //转移文件夹
        var moveFolderfun = function(){
            var cid = _cache.cid;
			
            if(cid.indexOf("_") != -1){
                cid = 0;
            }

            var node = _cache.doms[0];
            var from_aid = node.attr("area_id");
            var from_cid = node.attr("cate_id");
            var data = {
                from_aid: from_aid,
                from_cid: from_cid,
                to_aid: _cache.aid,
                to_cid: cid
            }
            $.ajax({
                url: PAGE_PATHS["MY"]+"/index.php?r=operate/index&ct=dir&ac=move_dir",
                type: "POST",
                data: data,
                dataType: "json",
                success: function(r){
                    if(r.state){
                        if(r.data.length){
                            var html = [];
                            for(var k in r.data){
                                var item = r.data[k]
                                html.push('<dd class="err"><ul><li class="file-name"><i class="file-type"></i>' + item.file_name + '</li><li class="file-rate">' + item.error + '</li></ul></dd>')
                            }
                            if(!_cache.resultBox){
                                _cache.resultBox = new _result();
                            }
                            _cache.resultBox.Open(function(){
                                _cache.resultBox.SetContent(html.join(""), data.to_aid, data.to_cid);
                            },_cache.base_win);
                        }
                        else{
                           Core.MinMessage.Show({
                                text: "转移成功", 
                                type: "suc", 
                                timeout: Core.CONFIG.MsgTimeout , 
                                window: _self
                            });
                            try{
                                if(Core.FileConfig.DataAPI) Core.FileConfig.DataAPI.Del(Core.FileConfig.aid, Core.FileConfig.cid, _cache.doms);
                            }catch(e){}
                        }
                        Core.Tree.DeleteNode(data["from_cid"]);
                        Core.Tree.Sandbox(r.dir);
                        _self.Close();
                    }
                    else{
                        Core.MinMessage.Show({
                            text: r.msg,
                            type: "err",
                            timeout: Core.CONFIG.MsgTimeout
                        });
                    }
                }
            })
        }
        
        //复制与移动文件
        var confirmFun = function(){
            var cid = _cache.cid;
			
            if(cid.indexOf("_") != -1){
                cid = 0;
            }			
            var data = {
                tid: _cache.list.join(","),
                aid: Core.FileConfig.aid,
                cid: Core.FileConfig.cid,
                _aid: _cache.aid,
                _cid: cid
            }
            var is_copy = _content.find("[rel='is_copy']").attr("checked");
            if(is_copy){
                _cache.op_type = "copy";
            }
            else{
                _cache.op_type = "move";
            }
            Core.MinMessage.Show({
                text: (_cache.op_type == "move"? "文件转移中，请稍候":"复制文件中，请稍候"), 
                type: "load", 
                window: _self
            });
            $.ajax({
                url: PAGE_PATHS["MY"]+"/index.php?r=operate/index&ct=file&ac=" + _cache.op_type,
                data: data,
                type: "POST",
                dataType: "json",
                success: function(r){
                    if(r.state){
                        Core.MinMessage.Show({
                            text: (_cache.op_type == "move"? "转移完成":"复制完成"), 
                            type: "suc", 
                            timeout: Core.CONFIG.MsgTimeout , 
                            window: _self
                        });
                        Core.SpaceData.Sync();
                        var html = [];
                        var dellist = [];
                        for(var k in _cache.doms){
                            var item = _cache.doms[k];
                            var fileName = item.find("[field='file_name']").html();
                            var icotype = item.attr("ico");
                            var fileId = item.attr("file_id");
                            var itemR = r.data[fileId]
                            var result = itemR.state? '<i class="icon ico-done"></i>' : itemR.msg;
                            if(itemR.state){
                                dellist.push(item);
                            }
                            html.push('<dd ' + (!itemR.state? 'class="err" title="' + itemR.msg + '"' : "") + '><ul><li class="file-name"><i class="file-type"></i>' + fileName + '</li><li class="file-rate">' + result + '</li></ul></dd>')
                        }
                        if(dellist && _cache.op_type == "move"){
                            try{
                            if(Core.FileConfig.DataAPI) Core.FileConfig.DataAPI.Del(Core.FileConfig.aid, Core.FileConfig.cid, dellist);
                            }catch(e){}
                        }
						
                        if(!_cache.resultBox){
                            _cache.resultBox = new _result();
                        }
                        _self.Close();
                        _cache.resultBox.Open(function(){
                            _cache.resultBox.SetContent(html.join(""), data._aid, data._cid);
                        },_cache.base_win);
                    }
                    else{
                        Core.MinMessage.Show({
                            text: typeof(r.msg)=='undefined'?"操作失败":r.msg, 
                            type: "err", 
                            timeout: Core.CONFIG.MsgTimeout , 
                            window: _self
                        });
                    }
                }
            })
        }
		
        this.SetConfig = function(arr, type, win){
            _content.find("[rel='is_copy_box']").hide();
            if(type == "copy" || type == "move"){
                var tid = [];
                for(var i = 0, len = arr.length; i < len; i++){
                    tid.push(arr[i].attr("file_id"));
                }
                _cache.list = tid;
                _content.find("[rel='is_copy_box']").show();
                _content.find("[rel='is_copy']").attr("checked", type == "copy");
            }
            _cache.doms = arr;
            _cache.op_type = type;
            _cache.base_win = win;
            
            if(type == "move_folder"){
                var node = _cache.doms[0];
                
                var from_cid = node.attr("cate_id");
                
                var treeBox = _content.find("[rel='tree']");
                var a = _content.find("[rel='tree']").find("a[cid='"+from_cid+"']");
                
                var li =  a.parent();
				var ul = li.parent();

				li.empty().remove();
				if(!ul.find("li").length){
					var pid = ul.attr("pid");
                    var dd = ul.parent();
					ul.empty().remove();
					treeBox.find("[cid='"+pid+"'] i[rel='open']").empty().remove();
                    if(pid.toString().indexOf("_0") != -1){
                        dd.hide();
                    }
				}
            }
        }
		
        this.RecvCallback = false;
    }
	
    var _result = function(){
        var _self = this,_resCache = {};
        var _content = $('<div class="file-copy" style="overflow:auto;"><dl class="file-list" rel="con"></dl></div>'+
            '<div class="dialog-bottom">'+
                '<div class="fr">'+
                    '<a href="javascript:;" class="button" btn="goto"><span class="btn-con">打开文件目录</span></a>'+
                    '<a href="javascript:;" class="button btn-gray" btn="close"><span class="btn-con">关闭</span></a>'+
                '</div>'+
            '</div>');
        Core.DialogBase.call(this,{
            title: '操作结果', 
            content: _content
        });	//继承 dialog
		
        this.Initial = function(){
            _content.find("[btn='goto']").click(function(){
                PageCTL.GOTO(_resCache.aid, _resCache.cid);
                window.setTimeout(function(){
                    _self.Close();
                },1);
                return false;
            })
            _content.find("[btn='close']").click(function(){
                _self.Close();
                return false;
            })
        }
		
        this.SetContent = function(html, aid, cid){
            _resCache.aid = aid;
            _resCache.cid = cid
            html = ' <dt><ul><li class="file-name">文件名</li><li class="file-rate">操作结果</li></ul></dt>' + html;
            _content.find("[rel='con']").html(html);
            if(_resCache.aid != undefined){
                _content.find('[btn="goto"]').show();
            }
            else{
                _content.find('[btn="goto"]').hide();
            }
        }
    }
	
    var _treeModel;
    return {
        Show: function(obj){
            Core.Tree.CheckIsLoad(function(){
                if(!obj.list || !obj.list.length){
                    Core.MinMessage.Show({
                        text: "请选择文件", 
                        timeout: Core.CONFIG.MsgTimeout, 
                        window: obj.win
                    });
                    return;
                }
                if(!_treeModel){
                    _treeModel = new _TreeSelect();
                }

                _treeModel.Open(function(){
                    _treeModel.RecvCallback = false;
                    _treeModel.RecvCallback = obj.callback;
                    _treeModel.SetConfig(obj.list, obj.type, obj.win);
                },obj.win);
            });
        }
    }
})();

/*选择文件对话框*/
Core.FileSelectDG = (function(){
    var _model = function(){
        var _self = this, _cache = {
            disClass: "btn-disabled"
        };
        var _content = $('<div class="file-select">' +
                            '<div class="directory-tree" rel="tree_box"></div>' +
                            '<iframe src="" frameborder="0" rel="js_iframe"></iframe>' +
                          '</div>' +
                            '<div class="dialog-bottom">'+
                                '<div class="fl" rel="msg_box"></div>'+
                                '<div class="fr">'+
                                    '<a href="javascript:;" class="button" btn="confirm">确定</a>'+
                                    '<a href="javascript:;" class="button btn-gray" btn="cancel">取消</a>'+
                                '</div>'+
                            '</div>');
        Core.DialogBase.call(this, {
            title: '请选择文件', 
            content: _content, 
            width: 750
        });
		
        var _frame = _content.find("[rel='js_iframe']");
		
        //点击树目录
        var clickTreeNode = function(ele){
            var aid = ele.attr("aid");
            var cid = ele.attr("cid");
            var isOpen = !(ele.find("i[rel='open']").hasClass("ino") && ele.hasClass("focus"));
            if(isOpen){
                Core.Tree.OpenChild(cid,[ele.parents("dl")]);
            }
            else{
                Core.Tree.HideChild(cid,[ele.parents("dl")]);
            }
	
            /*改变Iframe URL*/
            if(cid.toString().indexOf("_") != -1){
                cid = 0;
            }
			
            _cache.aid = aid;
            _cache.cid = cid;
			
            var tpl = "list_noside";
            
            if(_cache.aid == 3){
                tpl = "view_noside";
            }
            
            var url = "?ct=file&ac=userfile&tpl=" + tpl + "&aid=" + aid + "&cid=" + cid + "&_t=" + new Date().getTime();
            _frame.attr("src","");
            _frame.attr("src",url);
			
            _content.find('[rel="tree_box"]').find("a.focus").removeClass("focus");	
            ele.addClass("focus");
        }
		
        this.Initial = function(){			
            _content.find("[btn]").unbind("click").bind("click",function(){
                switch($(this).attr("btn")){
                    case "confirm":
                        if(!_cache.list || !_cache.list.length){
                            Core.MinMessage.Show({
                                text: "请选择文件", 
                                timeout: Core.CONFIG.MsgTimeout, 
                                window: _self
                            });
                            return;
                        }
                        switch(_cache.type){
                            case "cover":
                                //修改封面
                                Core.FileAjax.EditCover(_cache.cover_aid,_cache.cover_cid,_cache.list[0].attr("file_id"), function(r){
                                    if(r.state){
                                        Core.MinMessage.Show({
                                            text: "修改成功", 
                                            type:"suc", 
                                            timeout: Core.CONFIG.MsgTimeout
                                        });
                                    }
                                    else{
                                        Core.MinMessage.Show({
                                            text: r. msg, 
                                            type:"err", 
                                            timeout: Core.CONFIG.MsgTimeout
                                        });
                                    }
                                    _self.Close();
                                });
                                break;
                        }
						
                        break;
                    case "cancel":
                        _self.Close();
                        break;
                }
                return false;
            })
			
            var treeBox = _content.find('[rel="tree_box"]');
            var treeDom = Core.Tree.GetTree(20);
			
            var ul = $(document.createElement('dl'));
            for(var k in treeDom){
                treeDom[k].find("[aid='0']").parent().empty().remove();
                treeDom[k].find("[aid='5']").parent().empty().remove();
                ul.append(treeDom[k].clone(true));
            }
            treeBox.html("").append(ul);
			
            var aNode = ul.find("a[cid]");
            aNode.click(function(){
                var ele = $(this);
                clickTreeNode(ele);
                return false;
            })
			
            var selCid = _cache.default_cid? _cache.default_cid : "1_0";
            clickTreeNode(ul.find("a[cid='"+selCid+"']"));
            hideTreeNode(_cache.hide_aids);
            
        }
		
        var hideTreeNode = function(aids){
            var treeBox = _content.find('[rel="tree_box"]');
            if(!aids){
                var arr = [1,2,3,4];
                for(var i = 0, len = arr.length; i < len; i++){
                    treeBox.find("a[cid='"+(arr[i] + "_0")+"']").parent().show();
                }
            }
            else{
                for(var i = 0,len = aids.length; i < len; i++){
                    treeBox.find("a[cid='"+(aids[i] + "_0")+"']").parent().hide();
                }
            }
        }
        
        this.Setting = function(obj){
            _cache.users = obj.users;
            _cache.type = obj.type;
            _cache.cover_cid = obj.cover_cid;
            _cache.cover_aid = obj.cover_aid;
            _cache.default_cid = obj.default_cid;
            _cache.hide_aids = obj.hide_aids;
        }
        
        var _closeEvent = _self.Close;
        this.Close = function(){
            _frame.attr("src","");
            _closeEvent();
            _self.Callback = false;
        }
		
        this.Set = function(arr){
            _cache.list = arr;
            if(!_cache.list || !_cache.list.length){
                _content.find("[rel='msg_box']").html("请选择文件");
            }
            else{
                _content.find("[rel='msg_box']").html("已选择了" + arr.length + "个文件");
            }
        }
		
        this.Callback = false;
    }
	
    var _DG;
    return {
        Show: function(users, callback){
            Core.Tree.CheckIsLoad(function(){
                if(!_DG){
                    _DG = new _model();
                }
                _DG.Setting({
                    users:users, 
                    type: "send", 
                    default_cid: "1_0"
                });
                _DG.Open();
                _DG.Callback = callback;
            });
        },
        EditCover: function(aid, cid){
            Core.Tree.CheckIsLoad(function(){
                if(!_DG){
                    _DG = new _model();
                }
                var deault_cid = "3_0";
                if(Number(aid) == 3){
                    if(cid){
                        deault_cid = cid;
                    }
                }
                _DG.Setting({
                    cover_cid:cid, 
                    cover_aid:aid, 
                    type: "cover", 
                    hide_aids: [1,2,4,5,9], 
                    default_cid:deault_cid
                });
                _DG.Open();
            });
        },
        Select: function(arr){
            if(_DG){
                _DG.Set(arr);
            }
        }
    }
})();

/*
	设置文件描述对话框
*/
//编辑器设置内容回调
var editorCallBack = function(content){
    var box = document.getElementById(Core.CONFIG.EditTextArea);
    if(box){
        box.value = content;
    }
}

Core.FileReNameDG = (function(){
    var _mod;
    var _model = function(){
        var _self = this, _cache={};
        var _content = $('<div class="dialog-wrap popup-input">'+
                            '<input type="text" class="text" rel="file_name" />'+
                        '</div>'+
                        '<div class="dialog-bottom">'+
                            '<div class="fr">'+
                                '<a href="javascript:;" class="button" btn="confirm"><span class="btn-con">确定</span></a>'+
                                '<a href="javascript:;" class="button btn-gray" btn="cancel"><span class="btn-con">取消</span></a>'+
                            '</div>'+
                        '</div>');
        Core.DialogBase.call(this,{
            content: _content, 
            title: '重命名文件'
        });
        
        var renameFun = function(){
            var title = $.trim(_content.find('[rel="file_name"]').val());
            if(title == ""){
                 Core.MinMessage.Show({text: "请输入文件名", type: "war", timeout: Core.CONFIG.MsgTimeout, window:_self});
                _content.find('[rel="file_name"]').focus();
                return false;
                return;
            }
            var data = {
                file_id: _cache.file_id,
                file_name: title + _cache.suffix
            }
            //文件描述修改AJAX
            $.ajax({
                url:PAGE_PATHS["MY"]+"/index.php?r=operate/index&ct=file&ac=edit",
                data:data,
                dataType: "json",
                type: "POST",
                success: function(r){
                    if(r.state){
                        Core.MinMessage.Show({
                            text: "重命名成功", 
                            type: "suc", 
                            timeout: Core.CONFIG.MsgTimeout, 
                            window: Core.CONFIG.FileWindow
                        });
                        if(Core.FileConfig.DataAPI) Core.FileConfig.DataAPI.UpdateFile({
                            file_id: data.file_id, 
                            file_name:data.file_name
                        });
                    }
                    else{
                        Core.MinMessage.Show({
                            text: r.msg, 
                            type: "err", 
                            timeout: Core.CONFIG.MsgTimeout, 
                            window: Core.CONFIG.FileWindow
                        });
                    }
                }
            })
            _self.Close();
            
        }
        
        this.Initial = function(){
            _content.find("[rel='file_name']").bind("keydown", function(e){
                if(e.keyCode == 13){
                    renameFun();
                }
                else if(e.keyCode == 27){
                    _self.Close();
                }
            })

            _content.find("[btn]").bind("click", function(e){
                switch($(this).attr("btn")){
                    case "confirm":
                        renameFun();
                        break;
                    case "cancel":
                        _self.Close();
                        break;
                }
                return false;
            })
        }
        
        this.SetValue = function(file_id, file_name){
            _cache.file_id = file_id;
            var title = file_name;
            if(title.indexOf(".") != -1){
                _cache.suffix = title.substring(title.lastIndexOf("."), title.length);
                title = title.substring(0, title.lastIndexOf("."));
            }
            else{
                _cache.suffix = "";
            }
            _content.find('[rel="file_name"]').val(title);
            window.setTimeout(function(){
                _content.find('[rel="file_name"]').select();
            },20);
        }
    }
    
    
    return {
        Show: function(file_id, file_name){
            if(!_mod){
                _mod = new _model();
            }
            
            _mod.Open(function(){
                _mod.SetValue(file_id, file_name);
            });
        }
    }
})();

Core.FileDescDG = (function(){
    var _model = function(){
        var _self = this;
        var _cache_obj, _cache={};
		
        var _content = $('<div class="edit-box">'+
                            '<div class="editor-wrap">'+
                                '<textarea id="' + Core.CONFIG.EditTextArea + '" style="display: none;" name=""></textarea>'+
                                '<iframe id="js_ifrHtmlEditor" scrolling="no" frameborder="0" border="0" name="ifrHtmlEditor" src=""></iframe>'+
                            '</div>'+
                        '</div>'+
                        '<div class="dialog-bottom"><div class="fl">填写资源描述，使资源更受欢迎！</div>'+
                            '<div class="fr">' + 
                            '<a href="javascript:;" class="button" btn="confirm">确定</a>'+
                            '<a href="javascript:;" class="button btn-gray" btn="cancel">取消</a>'+
                            '</div>' + 
                        '</div>');
		
        Core.DialogBase.call(this,{
            content: _content, 
            title: '修改文件备注', 
            width:600
        });
		
        var _editorControl = (function(){
            var initState = false;
            var init = function(){
                if(!initState){
                    initState = true;
                    document.getElementById("js_ifrHtmlEditor").src = Core.CONFIG.EditPath + "&bind=" + Core.CONFIG.EditTextArea + "&_t=" + new Date().getTime();
                }
            }
			
            return {
                Get: function(){
                    return document.getElementById(Core.CONFIG.EditTextArea).value;
                },
                Set: function(content){
                    init();
                    document.getElementById(Core.CONFIG.EditTextArea).value = content;
                    window.setTimeout(function(){
                        document.getElementById("js_ifrHtmlEditor").src = Core.CONFIG.EditPath + "&bind=" + Core.CONFIG.EditTextArea + "&_t=" + new Date().getTime();
                    },10);
                },
                Height: function(value){
                    if(value != undefined){
                        $("#js_ifrHtmlEditor").height(value);
                    }
                    else{
                        return $("#js_ifrHtmlEditor").height();
                    }
                }
            }
        })();
		
        this.Initial = function(){
            _editorControl.Height(310);
            _content.find("[btn]").unbind("click").bind("click",function(){
                switch($(this).attr("btn")){
                    case "confirm":
                        var desc = _editorControl.Get();
                        var data = {
                            file_id: _cache_obj.file_id,
                            file_desc: desc
                        }
                        //文件描述修改AJAX
                        $.ajax({
                            url:PAGE_PATHS["MY"]+"/index.php?r=operate/index&ct=file&ac=edit",
                            data:data,
                            dataType: "json",
                            type: "POST",
                            success: function(r){
                                if(r.state){
                                    Core.MinMessage.Show({
                                        text: "编辑成功", 
                                        type: "suc", 
                                        timeout: Core.CONFIG.MsgTimeout, 
                                        window: Core.CONFIG.FileWindow
                                    });
                                    if(Core.FileConfig.DataAPI) Core.FileConfig.DataAPI.UpdateFile({
                                        file_id: data.file_id,
                                        desc: data.file_desc
                                    });
                                }
                                else{
                                    Core.MinMessage.Show({
                                        text: r.msg, 
                                        type: "err", 
                                        timeout: Core.CONFIG.MsgTimeout, 
                                        window: Core.CONFIG.FileWindow
                                    });
                                }
                            }
                        })
                        _self.Close();
                        break;
						
                    case "cancel":
                        _self.Close();
                        break;
                }
                return false;
            })
        }
		
        var _closeEvent = _self.Close;
		
        this.Close = function(){
            $("#js_ifrHtmlEditor").attr("src","");
            _closeEvent();
            _cache_obj = false;
        }

        this.SetValue = function(obj){
            _cache_obj = obj;
            _editorControl.Set(obj.value);
        }
    }
	
    var _editDG;
	
    return {
        Show: function(obj){
            if(!_editDG){
                _editDG = new _model();
            }
			
            _editDG.Open(function(){
                _editDG.SetValue(obj);
            }, Core.CONFIG.FileWindow);
        }
    }
})();

/*文件操作AJAX接口*/
Core.FileAjax = (function(){
    return {
        AllowCollect: function(list, is_collect){
            if(is_collect == 0 && !Core.FilePermission.Vip()){
                Core.VIPNotice.Upgrade();
                return false;
            }
            var file_ids = [];
            for(var i = 0, len = list.length; i < len; i++){
                var item = list[i];
                file_ids.push(item.attr("file_id"));
            }

            $.ajax({
                url: "?ct=file&ac=is_collect",
                type: "POST",
                data: {tid: file_ids.join(","), is_collect: is_collect},
                dataType: "json",
                cache: false,
                success: function(r){
                    if(r.state){
                        Core.MinMessage.Show({
                            text: "设置成功",
                            type: "suc",
                            timeout: Core.CONFIG.MsgTimeout
                        });
                        Core.FileConfig.DataAPI.AllowCollect(Core.FileConfig.aid, Core.FileConfig.cid, is_collect, list);
                    }
                    else{
                        Core.MinMessage.Show({
                            text: r.msg,
                            type: "err",
                            timeout: Core.CONFIG.MsgTimeout
                        });
                    }
                }
            })
        },
        GetFileDetail: function(file_id, callback){
            $.ajax({
                url: PAGE_PATHS["MY"]+"/index.php?r=operate/index&ct=file&ac=get&tid=" + file_id,
                type: "GET",
                dataType: "json",
                cache: false,
                success: function(r){
                    if(r.state){
                        if(callback){
                            callback(r.data);
                        }
                    }
                    else{
                        if(callback){
                            callback(false, r.msg);
                        }
                    }
                }
            })
        },
        GetDirDetail: function(aid, cid, callback){
            $.ajax({
                url: PAGE_PATHS["MY"]+"/index.php?r=operate/index&ct=file&ac=get&aid=" + aid + "&cid=" + cid,
                type: "GET",
                dataType: "json",
                cache: false,
                success: function(r){
                    if(r.state){
                        if(callback){
                            try{
                                callback(r.data);
                            }catch(e){}
                        }
                    }
                    else{
                        if(callback){
                            try{
                            callback(false, r.msg);
                            }catch(e){}
                        }
                    }
                }
            })
        },
        Star: function(tid, is_star, callback){
            var data = {};
            data["tid"] = tid;
            data["is_star"] = is_star;
            $.ajax({
            	url: PAGE_PATHS["MY"]+"/index.php?r=operate/index&ct=file&ac=star",
                data: data,
                dataType: "json",
                type: "POST",
                success: function(r){
                    if(r.state){
                        if(callback) callback(tid, is_star);
                        if(is_star){
                            Core.MinMessage.Show({
                                text: "成功加入我的最爱",
                                type: "suc",
                                timeout: Core.CONFIG.MsgTimeout
                            })
                        }
                    }
                    else{
                        Core.MinMessage.Show({
                            text: r.msg,
                            type: "err",
                            timeout: Core.CONFIG.MsgTimeout
                        })
                    }
                }
            })
        },
        SendFolder: function(users, aid, cid, desc,codeObj, callback){
            var userData = [];
            userData.push("aid=" + aid);
            userData.push("cid=" + cid);
            var ind = 0;
            for(var k in users){
                userData.push("user_id["+ind+"]=" + k + "&user_name["+ind+"]=" + encodeURIComponent(users[k]));
                ind++;
            }
            userData.push("body=" + encodeURIComponent(desc))
            if(codeObj.has_code){
                userData.push("msg_code=" + codeObj.code);
            }

            Core.MinMessage.Show({
                text: "文件夹发送中...", 
                type: "load", 
                timeout: Core.CONFIG.MsgTimeout
            });
            $.getScript(Core.CONFIG.Path.Msg + "/?ac=send&js_return=msg_callback_field&" + userData.join("&"), function(){
                if(window["msg_callback_field"]){
                    var r = window["msg_callback_field"];
                    if(r.state){
                        Core.MinMessage.Show({
                            text: "文件夹已成功发送", 
                            type: "suc", 
                            timeout: Core.CONFIG.MsgTimeout
                        });
                        if(callback){
                            callback(r);
                        }
                    }
                    else{
                        Core.MinMessage.Show({
                            text: r.message, 
                            type: "err", 
                            timeout: Core.CONFIG.MsgTimeout
                        });
                    }
                }

            })
        },
        SendFile: function(users, tids, aids, cids, desc,codeObj, callback){
            var userData = [];
            userData.push("aid=" + aids.join(","));
            userData.push("cid=" + cids.join(","));
            userData.push("file_id=" + tids.join(","));

            var ind = 0;
            for(var k in users){
                userData.push("user_id["+ind+"]=" + k + "&user_name["+ind+"]=" + encodeURIComponent(users[k]));
                ind++;
            }
            userData.push("body=" + encodeURIComponent(desc))
            if(codeObj.has_code){
                userData.push("msg_code=" + codeObj.code);
            }

            Core.MinMessage.Show({
                text: "文件发送中...", 
                type: "load", 
                timeout: Core.CONFIG.MsgTimeout
            });

            $.getScript(Core.CONFIG.Path.Msg + "/?ac=send&js_return=msg_callback_field&" + userData.join("&"), function(){
                if(window["msg_callback_field"]){
                    var r = window["msg_callback_field"];
                    if(r.state){
                        Core.MinMessage.Show({
                            text: "文件已成功发送", 
                            type: "suc", 
                            timeout: Core.CONFIG.MsgTimeout
                        });
                        if(callback){
                            callback(r);
                        }
                    }
                    else{
                        Core.MinMessage.Show({
                            text: r.message, 
                            type: "err", 
                            timeout: Core.CONFIG.MsgTimeout
                        });
                    }
                }

            })
        },
        _rbPassWord: function(callback){//回收站删除弹出的确认dialog
//            if(Core.FileAjax.RBPassWordSet){
//                Core.FileAjax.RBPassWordSet();
//                return;
//            }
            var passwordCon = $('<div class="dialog-wrap popup-input">'+
            	'<div class="dialog-title"><i class="i-hint ico-inf-l"></i>确认要删除选中的文件吗？</div>'+
                '</div>'+
                '<div class="dialog-bottom"><div class="fr">'+
                    '<a href="javascript:;" class="button" btn="confirm">确定</a>'+
                    '<a href="javascript:;" class="button btn-gray" btn="cancel">取消</a>'+
                '</div></div>');
            var passwordBox = new Core.DialogBase({
                title: '信息提示',
                content: passwordCon
            });

            passwordBox.Open(function(){
                passwordBox.warp.find("[rel='goto_set_pwd']").unbind("click").bind("click",function(){
                    window.setTimeout(function(){
                        passwordBox.Close();
                    }, 10);
                })
            });

            passwordCon.find("[btn]").bind("click",function(e){
                switch($(this).attr("btn")){
                    case "confirm":
                        if(callback){
                            callback(passwordCon.find("[rel='txt']"), function(){
                                passwordBox.Close();
                            });
                        }
                        break;
                    case "cancel":
                        passwordBox.Close();
                        break;
                }
                return false;
            })
            passwordCon.find("[rel='txt']").keydown(function(e){
                if(e.keyCode == 13){
                    if(callback){
                        callback(passwordCon.find("[rel='txt']"), function(){
                            passwordBox.Close();
                        });
                    }
                }
            })
//            passwordCon.find("[rel='txt']")[0].focus();
        },
        
        _rbClean: function(callback){//回收站清空文件弹出的确认dialog
          var cleanRbCon = $('<div class="dialog-wrap popup-input">'+
              	'<div class="dialog-title"><i class="i-hint ico-inf-l"></i>确认要清除回收站吗？</div>'+
                  '</div>'+
                  '<div class="dialog-bottom"><div class="fr">'+
                      '<a href="javascript:;" class="button" btn="confirm">确定</a>'+
                      '<a href="javascript:;" class="button btn-gray" btn="cancel">取消</a>'+
                  '</div></div>');
          var cleanRbBox = new Core.DialogBase({
              title: '信息提示',
              content: cleanRbCon
          });
          cleanRbBox.Open(function(){
        	  cleanRbBox.warp.find("[rel='goto_set_pwd']").unbind("click").bind("click",function(){
                  window.setTimeout(function(){
                	  cleanRbBox.Close();
                  }, 10);
              })
          });

          cleanRbCon.find("[btn]").bind("click",function(e){
              switch($(this).attr("btn")){
                  case "confirm":
                      if(callback){
                          callback(cleanRbCon.find("[rel='txt']"), function(){
                        	  cleanRbBox.Close();
                          });
                      }
                      break;
                  case "cancel":
                	  cleanRbBox.Close();
                      break;
              }
              return false;
          })
          cleanRbCon.find("[rel='txt']").keydown(function(e){
              if(e.keyCode == 13){
                  if(callback){
                      callback(cleanRbCon.find("[rel='txt']"), function(){
                    	  cleanRbBox.Close();
                      });
                  }
              }
          })
//          cleanRbCon.find("[rel='txt']")[0].focus();
      },
        RBPassWordSet: false,
        //清空回收站
        ClearRB: function(){
            Core.FileAjax._rbClean(function(input, hideFun){
                $.ajax({
                    url: PAGE_PATHS["MY"]+"/index.php?r=operate/index&ct=rb&ac=clean",
                    type: "POST",
                    dataType: "json",
                    data: {
                        "recycle_pass": input.val()
                    },
                    success: function(r){
                        if(r.state){
                            if(Core.FileConfig.DataAPI) Core.FileConfig.DataAPI.Reload();
                            if(hideFun){
                                hideFun();
                            }
                            Core.MinMessage.Show({
                                text: "成功清空回收站", 
                                type:"suc", 
                                timeout:Core.CONFIG.MsgTimeout
                            });
                            Core.CountSync.Sync();
                            Core.SpaceData.Sync(function(){
                            	Core.SpaceTop.Modify();
                            });
                        }
                        else{
                            Core.MinMessage.Show({
                                text:r.msg, 
                                type:"err", 
                                timeout:Core.CONFIG.MsgTimeout
                            });
                            if(input.length){
                                input[0].focus();
                            }
                        }
                    }
                })
            });
        },
        OneKeyRenew: function(win){
            var url = "?ct=file&ac=share";
            $.ajax({
                url: url,
                type: "POST",
                dataType: "json",
                data: {
                    aid:0,
                    cid:0,
                    is_batch:1
                },
                success: function(r){
                    if(r.state){
                        try{
                            if(Core.FileConfig.DataAPI) Core.FileConfig.DataAPI.Reload();
                        }catch(e){}
                        Core.MinMessage.Show({
                            text: "续期成功", 
                            type:"suc", 
                            window:win, 
                            timeout:Core.CONFIG.MsgTimeout
                        });
                    }
                    else{
                        Core.MinMessage.Show({
                            text: "续期失败", 
                            type:"err", 
                            window:win, 
                            timeout:Core.CONFIG.MsgTimeout
                        });
                    }
                }
            })
        },
        //删除回收站文件
        DeleteRB: function(tids, win){
            Core.FileAjax._rbPassWord(function(input, hideFun){
                $.ajax({
                    url: PAGE_PATHS["MY"]+"/index.php?r=operate/index&ct=rb&ac=del",
                    type: "POST",
                    dataType: "json",
                    data: {
                        tid: tids.join(","), 
                        "recycle_pass": input.val()
                    },
                    success: function(r){
                        if(r.state){
                            if(Core.FileConfig.DataAPI) Core.FileConfig.DataAPI.Reload();
                            Core.MinMessage.Show({
                                text: "成功删除回收站文件", 
                                type:"suc", 
                                timeout:Core.CONFIG.MsgTimeout
                            });
                            //modify by sylar   删除回收站时动态修改上部进度信息
                            Core.CountSync.Sync();
                            Core.SpaceData.Sync(function(){
                            	Core.SpaceTop.Modify();
                            });
                            
                            if(hideFun){
                                hideFun();
                            }
                        }
                        else{
                            Core.MinMessage.Show({
                                text:r.msg, 
                                type:"err", 
                                timeout:Core.CONFIG.MsgTimeout
                            });
                            if(input.length){
                                input[0].focus();
                            }
                        }
                    }
                })
            });
        },
        RestoreRB: function(tids, win){
            Core.Message.Confirm({
                text: "确认要还原选中的文件吗？", 
                type: "inf", 
                callback: function(r){
                    if(r){
                        $.ajax({
                            url: PAGE_PATHS["MY"]+"/index.php?r=operate/index&ct=rb&ac=revert",
                            type: "POST",
                            dataType: "json",
                            data: {
                                tid: tids.join(",")
                            },
                            success: function(result){
                                var sucState = true;
                                for(var k in result.data){
                                    if(!result.data[k].state){
                                        sucState = false;
                                    }
                                }
                                if(Core.FileConfig.DataAPI) Core.FileConfig.DataAPI.Reload();
                                Core.Tree.Sandbox(result.dir);
                                Core.CountSync.Sync();
                                Core.MinMessage.Show({
                                    text: "还原成功",
                                    type: "suc",
                                    timeout: Core.CONFIG.MsgTimeout
                                });
                                //TODO: 显示错误列表
                            }
                        })
                    }
                },
                win:win
            })
        },
        EditCover: function(aid, cid, tid, callback){
            $.ajax({
                url: PAGE_PATHS["MY"]+"/index.php?operate/index&r=ct=dir&ac=edit_cover",
                type: "POST",
                dataType: "json",
                data: {
                    tid: tid, 
                    aid: aid, 
                    cid: cid
                },
                success: function(result){
                    if(result.state){
                        //Core.MinMessage.Show({text: "设置成功", type: "suc", timeout: Core.CONFIG.MsgTimeout});
                        if(Core.FileConfig.DataAPI) Core.FileConfig.DataAPI.Reload();
                    }
                    if(callback){
                        callback(result);
                    }
                }
            })
        }
    }
})();

Core.FileAPI = (function(){
    return {
        _DownloadWin: false,
        RenewAll: function(callback){
            if(Core.FilePermission.Vip()){
                Core.Message.Confirm({
                    text: "您是否要一键续期所有分享文件?",
                    content: "您是尊贵的VIP贵宾，您不但拥有超长分享期限，点击“立即续期”即可续期您曾经分享的所有文件。",
                    title: "一键续期提醒",
                    type: "war",
                    callback:function(r){
                        if(r){
                            Core.MinMessage.Show({text: "正续期文件...", type: "load", timeout: 10000});
                            $.ajax({
                                url: "?ct=file&ac=one_key_renew",
                                type: "GET",
                                dataType: "json",
                                success: function(r){
                                    if(r.state){
                                        Core.MinMessage.Show({text: "续期成功", type: "suc", timeout: Core.CONFIG.MsgTimeout});
                                        callback && callback();
                                    }
                                    else{
                                        Core.MinMessage.Show({text: "续期失败", type: "err", timeout: Core.CONFIG.MsgTimeout});
                                    }
                                }
                            })
                        }
                    }
                });

            }
            else{
                Core.VIPNotice.Upgrade();
            }
        },
        ShareTO: function(list, perm){
            if(perm["share"]){
                Core.SendFileDG.Open(list, "file");
                return;
            }
            if(perm["send"]){
                Core.SendFileDG.Open(list, "friend");
                return;
            }
            if(perm["q"]){
                Core.SendFileDG.Open(list, "q");
                return;
            }
            if(perm["weibo"]){
                Core.SendFileDG.Open(list, "weibo");
                return;
            }
        },
        //下载
        Download: function(pick_code,win){ 
        	url  = PAGE_PATHS["MY"]+"/index.php?r=operate/index&ct=pickcode&ac=download&pickcode="+pick_code;
        	window.location.href=url;
//            $.ajax({
//                url: "/index.php?r=operate/index&ct=pickcode&ac=download",
//                data: {pickcode: pick_code},
//                type: "POST",
//                success: function(r){
//                }
//            })
//            if(Core.SpaceData.IsNoSpace() && Croe.FilePermission.VipExpLimit()){
//                Core.VIPNotice.Upgrade();
//                return;
//            }
//            alert(Core.CONFIG.Path.OS);
//            var url = Core.CONFIG.Path.OS + "?ct=pickcode&ac=download&pickcode=" + pick_code + "&_t=" + new Date().getTime();
//            var con = $('<iframe style="width:100%; height:200px; background:#fff;" frameborder=0 src="'+url+'"></iframe>');
//            Core.FileAPI._DownloadWin = new Core.DialogBase({
//                title: '文件快速下载',
//                content: con
//            });
//            Core.FileAPI._DownloadWin.Open(null, win);
        },
        OpenNewWindow: function(url){
            var form = document.createElement("form");
            form.action = url;
            form.target = "_blank";
            form.method = "post";
            document.body.appendChild(form);
            form.submit();
            window.setTimeout(function(){
                document.body.removeChild(form);
            }, 30);
        },
        DownloadList: function(items){
            var uDown;
            try{
                uDown=new ActiveXObject("UDiskAgent.UDiskAgentObj");
            }catch(e){
                if (confirm("您还没有安装“云盘”专用软件，本资源需要先安装云盘专属客户端才能够实现高速下载。\n\n请点击“确定”，立即下载该软件！")) {
                    Core.FileAPI.OpenNewWindow("http://pc.com");
                }
                return false;
            }
                var arr = [];
                arr.push(Core.CONFIG.Path.OS);
                for(var i = 0, len = items.length; i < len; i++){
                    var item = items[i];
                    arr.push(item.url + ";" + encodeURIComponent(item.file_name));
                }
                try{
                    uDown.DownAllLink2(arr.join("|"));
                }catch(e){
                    if (confirm("您的“云盘”专用软件需要升级。请点击“确定”，立即下载最新版软件！")) {
                        Core.FileAPI.OpenNewWindow("http://pc.com");

                    }
                    return false;
                }

            return true;
        },
        UDownDownload: function(list){
            if(list && list.length){
                var arr = [];
                for(var i = 0, len = list.length; i < len; i++){
                    var item = list[i];
                    var url = Core.CONFIG.Path.OS + ((item.attr("file_type") == "1")? "file/" : "folder/" ) + item.attr("pick_code");
                    arr.push({url: url, file_name: item.find('[field="file_name"]').attr("title")});
                }
                Core.FileAPI.DownloadList(arr);
                
            }
            else{
                Core.MinMessage.Show({text: "请先选择文件", type: "war", timeout:Core.CONFIG.MsgTimeout});
            }
        },
        //公告
        Notice: function(nid){
            //?ct=notice&ac=notice_list&nid=76&s=0
            var url = "?ct=notice&ac=notice_list&nid="+nid+"&s=0&_t=" + new Date().getTime();
            var con = $('<iframe style="width:100%; height:500px; background:#fff;" frameborder=0 src="'+url+'"></iframe>');
            var noticeBox = new Core.DialogBase({
                title: '系统公告',
                content: con,
                width: 800
            });
            noticeBox.Open(null);
        },
        //编辑同步盘文件名称
        EditSyncFileName: function(obj){
            if(obj.type == "f"){
                if(obj.fileName.lastIndexOf(".") == -1){
                    obj.suffix = "";
                }
                else{
                    var name = obj.fileName.substring(0,obj.fileName.lastIndexOf("."));
                    obj.suffix = obj.fileName.substring(obj.fileName.lastIndexOf("."));
                    obj.fileName = name;
                }
            }
            else{
                obj.suffix = "";
            }

            var editCon = $('<div class="dialog-wrap popup-input">'+
                                '<input type="text" rel="txt" class="text" value="' + obj.fileName + '" />'+
                            '</div>'+
                            '<div class="dialog-bottom">'+
                                '<div class="fr">' +
                                    '<a href="javascript:;" class="button" btn="confirm"><span class="btn-con">确定</span></a>'+
                                    '<a href="javascript:;" class="button btn-gray" btn="cancel"><span class="btn-con">取消</span></a>'+
                                '</div>' +
                            '</div>');
            var editBox = new Core.DialogBase({
                title: '重命名',
                content: editCon
            });

            editBox.Open(null);

            editCon.find("[rel='txt']").val(obj.fileName);


            //Rename Function
            var renameFolderFun = function(e){
                var model = e.data.model;
                //修改名称
                var input = editCon.find("[rel='txt']");
                var vals = $.trim(input.val());
                if(vals == ""){
                    Core.MinMessage.Show({
                        text: "请输入内容", 
                        timeout: Core.CONFIG.MsgTimeout, 
                        type:"err"
                    });
                    input.focus();
                    return;
                }
                model.fileName = vals + model.suffix;
                var newPath = model.path + model.fileName;
                if(model.callback){
                    model.callback(model.key, newPath, function(){
                        editBox.Close();
                    });
                }
            }

            editCon.find("[rel='txt']").bind("keyup", {
                model: obj
            }, function(e){
                if(e.keyCode == 13){
                    renameFolderFun(e);
                }
                else if(e.keyCode == 27){
                    editBox.Close();
                }
            })

            editCon.find("[btn]").bind("click", {
                model: obj
            }, function(e){
                switch($(this).attr("btn")){
                    case "confirm":
                        renameFolderFun(e);
                        break;
                    case "cancel":
                        editBox.Close();
                        break;
                }
                return false;
            })

            editCon.find("[rel='txt']")[0].select();
        },
        MoveSyncFile: function(list, callback){
            var id = list.find("input:checkbox").val();
            $.ajax({
                url: PAGE_PATHS["MY"]+"/index.php?r=operate/index&ct=file&ac=move_box",
                data: {aid: 1, cid: 0, id: id},
                type: "POST",
                success: function(r){

                    if(callback) callback();
                }
            })
        },
        GetCopyText: function(list){
            var strArr = [];
            for(var i = 0, len = list.length; i < len; i++){
                var item = list[i];
                var url = Core.CONFIG.Path.OS + ((item.attr("file_type") == "1")? "file/" : "folder/" ) + item.attr("pick_code");
                var file_name;

                if(item.attr("file_type") == "1"){
                    file_name = item.find('[field="file_name"]').attr("title");
                }
                else{
                    file_name = item.attr("cate_name");
                }

                strArr.push(url + "#\r\n" + file_name);
            }
            return strArr.join("\r\n");
        },
        //删除待续传文件
        DeleteInterrupt: function(pick_code, tid, aid, cid){
            Core.Message.Confirm({
                text: "确认要删除文件吗？",
                type: "war",
                callback: function(res){
                    if(res){
                        var data = {
                            tid: tid,
                            aid: aid,
                            cid: cid
                        }
                        $.ajax({
                            url: "?ct=file&ac=delete_interrupt",
                            data: data,
                            type: "POST",
                            dataType: "json",
                            success: function(r){
                                if(r.state){
                                    Core.MinMessage.Show({
                                        text: "删除成功", 
                                        type: "suc", 
                                        timeout: Core.CONFIG.MsgTimeout
                                    });
                                    Core.Upload.DeleteByPickCode(pick_code);
                                    if(Core.FileConfig.DataAPI) Core.FileConfig.DataAPI.Reload();
                                }
                                else{
                                    Core.MinMessage.Show({
                                        text: "删除失败", 
                                        type: "suc", 
                                        timeout: Core.CONFIG.MsgTimeout
                                    });
                                }
                            }
                        })
                    }
                }
            })
        }
    }
})();

/*同步收件箱与回收站数量*/
Core.CountSync = (function(){
    var _rbDom;
    return {
        Bind: function(rbDom){
            _rbDom = rbDom;
        },
        Sync: function(){
            if(_rbDom){
                $.ajax({
                    url: PAGE_PATHS["MY"]+"/index.php?r=operate/index&ct=rb&ac=get_num",
                    type: "GET",
                    cache: false,
                    dataType: "json",
                    success: function(r){
                        try{
                            _rbDom.html(Number(r.count)? r.count : "");
                        }catch(e){}
                    }
                })
            }
        }
    }
})();

Core.SendFileDG = (function(){
    var _mod, _api, _list, _defaultType, _permission;
    
    var _model = function(){
        var _self = this, _cache = { };
        var _content = $('<div><div style="width:550px; height:422px;">'+
                            '<iframe src="" frameborder="0" rel="frame" style="width:550px; height:422px;"></iframe>'+
                         '</div>' +
                            '<div class="dialog-bottom" rel="bottom">'+
                                '<div class="fr">'+
                                    '<a href="javascript:;" class="button btn-green" btn="confirm">立即分享</a>'+
                                    '<a href="javascript:;" class="button btn-gray" btn="cancel">取消</a>'+
                                '</div>'+
                            '</div></div>');
        Core.DialogBase.call(this, {
            title: '分享', 
            content: _content, 
            width: 550
        });
        
        var _closeFun = _self.Close;
        this.IsOpen = false;
        this.Close = function(){
            _content.find("[rel='frame']").attr("src","");
            _self.IsOpen = false;
            _closeFun();
            _permission = false;
        }
        
        this.Initial = function(){
            var url, ac = "friend_search";
            _self.IsOpen = true;
            var h = 422;
            var bottom = _content.find("[rel='bottom']");
            bottom.show();
            var confirmBtn = _content.find('[btn="confirm"]');
            var params = "";
            confirmBtn.html("立即分享").show();
            if(_defaultType){
                switch(_defaultType){
                    //快速分享结果显示
                    case "file":
                        ac = "share_file";
                        confirmBtn.html("生成分享地址");
                        confirmBtn.hide();
                        break;
                    case "file_result":
                        ac = "share_file";
                        params = "&is_result=1";
                        confirmBtn.hide();
                        break;
                    //圈子结果显示
                    case "q_result":
                        ac = "share_q";
                        params = "&is_result=1";
                        confirmBtn.hide();
                        break;
                    case "q":
                        ac = "share_q";
                        break;
                    case "weibo":
                        ac = "share_weibo";
                        break;
                }
            }
            url = "?ct=file&ac=" + ac + params + "&_t=" + new Date().getTime();
            
            var ifrm = _content.find("[rel='frame']");
            ifrm.attr("src", url);
            ifrm.height(h).parent().height(h);
            
            _content.find("[btn]").unbind("click").bind("click", function(){
                
                var btnType = $(this).attr("btn");
                
                switch(btnType){
                    case "confirm":
                        if(!_api){
                            Core.MinMessage.Show({
                                text: "数据未加载完成，请稍候",
                                type: "err",
                                timeout: Core.CONFIG.MsgTimeout,
                                window: _self
                            })
                        }
                        switch(_api.Key){
                            //分享到微博
                            case "share_file":
                                var action = Core.FileMenu.Action("share_dataaccess");
                                action && action(_list, "share", function(){
                                    Core.SendFileDG.Open(_list,"file_result");
                                });
                                break;
                            
                            case "share_weibo":
                                var action = Core.FileMenu.Action("share_dataaccess");
                                action && action(_list, "share", function(){
                                    //Core.SendFileDG.Open(_list,"file_result");
                                
                                    _api.Send(function(){
                                        Core.MinMessage.Show({
                                            text: "成功分享到微博",
                                            type: "suc",
                                            timeout: Core.CONFIG.MsgTimeout,
                                            window: _self
                                        })
                                        _self.Close();
                                    });
                                });
                                break;
                            //分享到圈子
                            case "share_q":
                                _api.Send(function(){
                                    Core.MinMessage.Show({
                                        text: "成功分享到圈子",
                                        type: "suc",
                                        timeout: Core.CONFIG.MsgTimeout,
                                        window: _self
                                    })
                                    _self.Close();
                                    //Core.SendFileDG.Open(_list, "q_result");
                                });
                                break;
                            //分享给用户
                            case "share_user":
                                var users = _api.GetUser();
                                if(!users){
                                    Core.MinMessage.Show({
                                        text: "请先选择好友",
                                        type: "war",
                                        timeout: Core.CONFIG.MsgTimeout,
                                        window: _self
                                    })
                                }
                                else{
                                    var sendconfig = _api.GetConfig();
                                    if(sendconfig){
                                        if(!(sendconfig.day_limit - sendconfig.day_sent)){
                                            Core.MinMessage.Show({
                                                text: "抱歉,今天您不可以再发送文件给好友了",
                                                type: "war",
                                                timeout: Core.CONFIG.MsgTimeout,
                                                window: _self
                                            })
                                            return false;
                                        }
                                        //抱歉,您一次发送的文件数量过多
                                        if(_list.length > sendconfig.single_limit){
                                            Core.MinMessage.Show({
                                                text: "抱歉,您一次只能发送" + sendconfig.single_limit + "个文件",
                                                type: "war",
                                                timeout: Core.CONFIG.MsgTimeout,
                                                window: _self
                                            })
                                            return false;
                                        }
                                    }
                                    
                                    //send
                                    var desc = _api.GetDesc();
                                    if(desc == ""){
                                        Core.MinMessage.Show({
                                            text: "请输入备注",
                                            type: "war",
                                            timeout: Core.CONFIG.MsgTimeout,
                                            window: _self
                                        })
                                        return false;
                                    }

                                    var codeObj = _api.GetCode();
                                    if(codeObj.has_code && codeObj.code == ""){
                                        Core.MinMessage.Show({
                                            text: "请输入验证码",
                                            type: "war",
                                            timeout: Core.CONFIG.MsgTimeout,
                                            window: _self
                                        })
                                        return false;
                                    }
                                    
                                    if(_list.length == 1 && _list[0].attr("file_type") == "0"){
                                        var aid = _list[0].attr("area_id");
                                        var cid = _list[0].attr("cate_id");
                                        Core.FileAjax.SendFolder(users, aid, cid, desc, codeObj , function(r){
                                            _self.Close();
                                        })
                                    }
                                    else{
                                        var tids = [];
                                        var aids = [];
                                        var cids = [];
                                        for(var i = 0, len = _list.length; i < len; i++){
                                            tids.push(_list[i].attr("file_id"));
                                            aids.push(_list[i].attr("area_id"));
                                            cids.push(_list[i].attr("p_id"));
                                        }

                                        Core.FileAjax.SendFile(users, tids, aids, cids, desc, codeObj , function(r){
                                            _self.Close();
                                        })
                                    }
                                }
                                break;
                        }
                        
                        break;
                    case "cancel":
                        _self.Close();
                        break;
                }
                return false;
            })
        }
        
        this.SetButtonValue = function(){
            
        }
    }
    
    return {
        Open: function(list, type){
            _defaultType = type;
            if(_defaultType == "friend"){
                if(list && list.length == 1){
                    var item = list[0];
                    if(item.attr("file_type") == "0" && !Core.FilePermission.Vip()){
                        Core.VIPNotice.Upgrade();
                        return;
                    }
                }
            }
            
            if(!_mod){
                _mod = new _model();
            }
            _api = false;
            _list = list;
            
            if(_mod.IsOpen){
                _mod.Close();
            }
            switch(Core.FileConfig.aid){
                case 1:case 2:case 3:case 4:case 5:case 9:
                    _permission = Core.FileMenu.CheckType(Core.FileConfig.aid, Core.FileConfig.cid,list);
                    if(Core.FilePermission.VipExp() && Core.SpaceData.IsNoSpace()){
                        var arr = [];
                        for(var i = 0, len = _permission.length; i < len; i++){
                            if(_permission[i] != "q" && _permission[i] != "weibo"){
                                arr.push(_permission[i]);
                            }
                        }
                        _permission = arr;
                    }
                    break;
                default:
                    if(Core.FilePermission.VipExp() && Core.SpaceData.IsNoSpace()){
                        _permission = ["share", "send"];
                    }
                    else{
                        _permission = ["share", "send", "q"];
                    }
                    
                    break;
            }
            
            _mod.Open();
        },
        Close: function(){
            if(_mod){
                _mod.Close();
            }
        },
        GetFileList: function(){
            return _list;
        },
        GetPermission: function(){
            return _permission;
        },
        SetAPI: function(api){
            _api = api;
            if(_mod){
                _mod.SetButtonValue();
            }
        }
    }
})();

/*高级搜索*/
Core.SearchFileDG = (function(){
    var _mod, _api;
    
    var _model = function(){
        var _self = this, _cache = { };
        var _content = $('<div class="advanced-search">'+
                            '<dl>'+
                                '<dt>关键字：</dt>'+
                                '<dd>'+
                                    '<input type="text" name="" rel="search_value" class="text" />'+
                                '</dd>'+
                                '<dt>所属目录：</dt>'+
                                '<dd>'+
                                    '<select name="" rel="search_aid">'+
                                        '<option value="-1">所有文件</option>' +
                                        '<option value="1">我的文件</option>' +
                                        '<option value="2">我的文档</option>' +
                                        '<option value="3">我的相册</option>' +
                                        '<option value="4">我的音乐</option>' +
                                        '<option value="9">我的视频</option>' +
                                    '</select>'+
                                '</dd>'+
                                '<dt>操作时间：</dt>'+
                                '<dd>'+
                                    '<select name="" rel="search_date">'+
                                        '<option value="0">所有时间</option>' +
                                        '<option value="1">最近一天</option>' +
                                        '<option value="3">最近三天</option>' +
                                        '<option value="7">最近一周</option>' +
                                        '<option value="30">最近一个月</option>' +
                                    '</select>'+
                                '</dd>'+
                            '</dl>'+
                            '<div class="search-bottom"><a href="javascript:;" class="button" btn="search_btn">开始搜索</a></div>'+
                        '</div>');
        Core.DialogBase.call(this, {
            title: '高级搜索', 
            content: _content
        });
        
        this.Initial = function(){
            _content.find("[btn='search_btn']").bind("click", function(){
                var searchVal = $.trim(_content.find("[rel='search_value']").val());
                var aid = _content.find("[rel='search_aid']").val();
                var date = _content.find("[rel='search_date']").val();
                if(searchVal == ""){
                    Core.MinMessage.Show({
                        text: "请输入搜索内容",
                        type: "war",
                        timeout: Core.CONFIG.MsgTimeout,
                        window: _self
                    })
                    return false;
                }
                if(_api){
                    _api({
                        search_value: encodeURIComponent(searchVal),
                        aid: aid,
                        date: date
                    });
                }
                _self.Close();
                return false;
            })
        }
        
        this.SetValue = function(val){
            var input = _content.find('[rel="search_value"]');
            input.val(val);
            window.setTimeout(function(){
                input.focus();
                input.select();
            }, 20);
        }
    }
    
    return {
        Show: function(val, api){
            if(!_mod){
                _mod = new _model();
            }
            _api = api;
            _mod.Open(function(){
                _mod.SetValue(val);
            })
        }
    }
})();

/**
 * 加密文件
 */
Core.PrivacyDG = (function(){
    var _mod, _cacheNode, _lock_file = true;
    
    var _model = function(){
        var _self = this, _cache = { };
        var _content = $('<div><div class="pwd-lock"><i class="ico-lock"></i>'+
                            '<h3>访问密码</h3>'+
                            '<div class="con">当您的朋友访问文件地址时，需要输入您设置的访问密码才可以下载文件，传递重要文件时更安全了。</div>'+
                        '</div>'+
                        '<dl class="pwd-box" vip="0">'+
                            '<dt rel="has_pwd">当前密码：</dt>'+
                            '<dd rel="has_pwd" txt="pwd_con">01234567890123</dd>'+
                            '<dt>新密码：</dt>'+
                            '<dd>'+
                                '<input type="text" class="text" rel="pwd" />'+
                                '<span class="hint-text text-err" style="display:none;" txt="txt_err"><i></i>不得超过15个字</span> </dd>'+
                            '<dt>留言：</dt>'+
                            '<dd>'+
                                '<textarea rel="ques"></textarea>'+
                            '</dd>'+
                        '</dl>' +
                        '<div class="pwd-vip" style="display:none;padding:80px 30px;" vip="1">'+
                            '<h3><span><i class="i-hint ico-war"></i>您还不是VIP会员，暂无此功能特权！</span></h3>'+
                            '<div class="con"><a href="'+Core.CONFIG.Path.VIP_ORDER+'/?p=privacy" target="_blank" class="button btn-red">立即升级为VIP</a></div>'+
                        '</div>'+
                        '<div class="dialog-bottom" vip="0">'+
                            '<div class="fr">'+
                                '<a href="javascript:;" class="button" btn="confirm">确定</a>'+
                                '<a href="javascript:;" class="button btn-gray" btn="cancel">取消</a>'+
                            '</div>'+
                        '</div><div>');
        Core.DialogBase.call(this, {
            title: '设置访问密码', 
            content: _content, 
            width: 550
        });
        
        this.Initial = function(){
            _content.find("[vip]").hide();
            var state;
            if(_cacheNode.attr("file_type") == "1"){
                state = Core.FilePermission.LockFile(Core.FileConfig.aid);
            }
            else{
                state = Core.FilePermission.LockDir(_cacheNode.attr("area_id"));
            }
            if(!state){
                _content.find("[vip='1']").show();
                return;
            }
            _content.find("[vip='0']").show();
            _content.find("[btn]").unbind("click").bind("click", function(){
                switch($(this).attr("btn")){
                    case "confirm":
                        if(_cacheNode.attr("file_type") == "1"){
                            //加密文件
                            //?ct=file&ac=edit
                            var data = {};
                            data.answer = $.trim(_content.find("[rel='pwd']").val());
                            data.question = $.trim(_content.find("[rel='ques']").val());
                            data.file_id = _cacheNode.attr("file_id");
                            data.aid = Core.FileConfig.aid;
                            data.cid = Core.FileConfig.cid;
                            $.ajax({
                                url: "?ct=file&ac=lock",
                                data: data,
                                type: "POST",
                                dataType: "json",
                                success: function(r){
                                    if(r.state){
                                        Core.MinMessage.Show({
                                            text: "成功加密文件",
                                            type: "suc",
                                            timeout: Core.CONFIG.MsgTimeout
                                        });
                                        Core.FileConfig.DataAPI.Privacy(Core.FileConfig.aid, Core.FileConfig.cid, data, [_cacheNode]);
                                    }
                                    else{
                                        Core.MinMessage.Show({
                                            text: r.msg,
                                            type: "war",
                                            timeout: Core.CONFIG.MsgTimeout
                                        });
                                    }
                                    _self.Close();
                                }
                            })
                            
                        }
                        else{
                            //加密文件夹
                            var data = {};
                            data.answer = $.trim(_content.find("[rel='pwd']").val());
                            data.question = $.trim(_content.find("[rel='ques']").val());
                            data.aid = _cacheNode.attr("area_id");
                            data.cid = _cacheNode.attr("cate_id");
                            $.ajax({
                                url: "?ct=dir&ac=lock",
                                data: data,
                                type: "POST",
                                dataType: "json",
                                success: function(r){
                                    if(r.state){
                                        Core.MinMessage.Show({
                                            text: "成功加密文件夹",
                                            type: "suc",
                                            timeout: Core.CONFIG.MsgTimeout
                                        });
                                        var dirNode = Core.FileConfig.DataAPI.GetDir(data.cid);
                                        if(dirNode){
                                            Core.FileConfig.DataAPI.Privacy(Number(data.aid), Core.FileConfig.cid, data, [dirNode]);
                                        }
                                    }
                                    else{
                                        Core.MinMessage.Show({
                                            text: r.message,
                                            type: "war",
                                            timeout: Core.CONFIG.MsgTimeout
                                        });
                                    }
                                    _self.Close();
                                }
                            })
                        }
                        break;
                    case "cancel":
                        _self.Close();
                        break;
                }
                return false;
            })
            
            var pwd = _cacheNode.attr("file_pwd");
            if(pwd){
                _content.find("[rel='has_pwd']").show();
                _content.find("[txt='pwd_con']").html(pwd);
                
            }
            else{
                _content.find("[rel='has_pwd']").hide();
            }
            
            var ques = _cacheNode.find('[field="ext3"]').val();
            _content.find("[rel='ques']").val(ques);
            _content.find("[rel='pwd']").val("");
            window.setTimeout(function(){
                _content.find("[rel='pwd']").focus();
            }, 50);
            
        }
    }
    
    return {
        File: function(node){
            _cacheNode = node;
            if(!_mod){
                _mod = new _model();
            }
            _lock_file = true;
            if(!_cacheNode.attr("has_pass")){
                _mod.Open();
            }
            else{
                if(!_cacheNode.attr("file_pwd") && _cacheNode.attr("file_type") == "1"){
                    Core.FileAjax.GetFileDetail(_cacheNode.attr("file_id"), function(r){
                        _cacheNode.attr("file_pwd", r.file_answer);
                        _cacheNode.find('[field="ext3"]').val(r.file_question);
                        
                        _mod.Open();
                    })
                }
                else{
                    _mod.Open();
                }
            }
        },
        Folder: function(aid, cid){
            _cacheNode = $("<div></div>");
            _cacheNode.attr("area_id", aid);
            _cacheNode.attr("cate_id", cid);
            
            if(!_mod){
                _mod = new _model();
            }
            _lock_file = false;
            Core.FileAjax.GetDirDetail(aid, cid,  function(r){
                _cacheNode.attr("file_pwd", r.password);
                _cacheNode.find('[field="ext3"]').val(r.ext3);
                _mod.Open();
            })
        }
    }
})();

/*用户权限*/
Core.FilePermission = (function(){
    var _per;
    
    return{
        Set: function(data){
            _per = data;
        },
        Shared: function(aid){
            aid = Number(aid);
            if(!_per) return false;
            if(aid == 3 || aid == 4){
                return false;
            }
            return true;
        },
        SharedDir: function(aid){
            aid = Number(aid);
            if(!_per) return false;
            var txt = aid + "|";
            return _per.share_dir.indexOf(txt) != -1;
        },
        Vip: function(){
            if(!_per) return false;
            return _per.is_vip;
        },
        VipExp: function(){
            if(!_per) return false;
            return _per.is_vip_exp;
        },
        VipExpLimit: function(){
            if(!_per) return false;
            return _per.is_vip_exp_limit;
        },
        LockFile: function(aid){
            aid = Number(aid);
            if(!_per) return false;
            if(aid == 3 || aid == 4){
                return false;
            }
            return _per.lock_file;
        },
        LockDir: function(aid){
            aid = Number(aid);
            if(!_per) return false;
            if(aid == 3 || aid == 4){
                return false;
            }
            return _per.lock_dir;
        }
    }
})();

/*
 * 浮动菜单
 */
Core.FileMenu = (function(){
    var _cache = {
        specil: {
            "5": {"edit":1,"edit_name":1, "delete": 1, "download": 1},
            "30": {"edit":1,"edit_name":1, "renew":1, "download": 1, "cancelshare":1, "copylink": 1, "privacy": 1},   //我的分享
            "31": {"edit":1,"edit_name":1, "shareto": 1, "download": 1, "copylink": 1, "privacy": 1},   //我的最爱
            "32": {"edit":1,"edit_name":1, "shareto": 1, "download": 1, "copylink": 1, "privacy": 1},   //最近上传
            "33": {"delete": 1},   //待续传文件
            "34": {"edit":1,"edit_name":1, "read":1, "shareto": 1, "download": 1, "copylink": 1, "privacy": 1}    //最近浏览
        },
        setting: {
            onemusic: ["edit", "edit_name", "download", "send", "copy", "move", "delete", "play", "q", "shareto"],	//选择了一个音乐文件
            onephoto: ["edit", "edit_name", "download", "send", "copy", "move", "delete", "view","q", "shareto"],	//选择了一张图片
            onemovie: ["edit", "edit_name", "download", "send", "copy", "move", "delete","q", "shareto"],
            onedocument: ["edit", "edit_name", "download", "send", "copy", "move", "delete", "read", "weibo", "q", "shareto"],   //选中了一份文档
            onefile: ["edit","edit_name", "download", "send", "copy", "move", "delete", "weibo", "q", "shareto"],	//选中单个文件
            onefolder: ["delete", "shareto", "send", "edit_name"],	//选中单个文件夹
            onefoldercover: ["cover"],
            onesharefolder: ["copylink", "weibo"],	//单个文件夹是否已分享
            share: ["copylink", "cancelshare"],	//
            renew: ["renew"],
            cancelshare: ["share"],
            sharefile: ["unloading", "cancelunloading"],
            lock: ["privacy"],
            movefolder: ["move"],
            fewmusic: ["copy", "send", "move", "delete", "play", "shareto", "q"],	//选择了多个音乐文件
            fewphoto: ["copy", "send", "move", "delete", "view","shareto", "q"],	//选择了多张图片
            fewmovie: ["copy", "send", "move", "delete","shareto", "q"],
            fewfile: ["copy", "send", "shareto", "move", "delete", "shareto", "q", "weibo"],
            fewfolder: ["delete"],
            fewfandfl: ["delete"],	//选中了多个文件夹与文件
            onekey: ["onekeyrenew"],
            rb: ["remove"],
            rbfile: ["rb_delete", "restore"],
            sentfile: ["exp_delete"],
            expfile: ["exp_delete", "exp_recv"],
            sync:["sync_refresh"],
            syncfile: ["sync_delete"]
        }
    }, _main_top = 37, _main_left=155, _opBox;
    
    if($.browser.msie){
        _cache.setting.fewmusic.push("download");
        _cache.setting.fewphoto.push("download");
        _cache.setting.fewmovie.push("download");
        _cache.setting.fewfile.push("download");
    }
    
    var _opcBoxTemp = '<div style="z-index: 9000000;background: none repeat scroll 0 0 black;height: 100%;left: 0;position: absolute;top: 0;width: 100%;filter:alpha(opacity=0.15);-moz-opacity:0;opacity:0;display:none;" onselectstart="return false;"></div>';
    
    var showopbox = function(hideFun){
        if(!_opBox){
            _opBox = $(_opcBoxTemp);
            $(document.body).append(_opBox);
        }
        _opBox.show();
        _opBox.unbind("mousedown").bind("mousedown", function(e){
            hideFun && hideFun(e);
            $(this).hide();
        });
    }
    
    var hideopbox = function(){
        if(_opBox){
            _opBox.hide();
        }
    }
    
    var getSelFilesData = function(arr){
        var data = {
            aid: Core.FileConfig.aid,
            pid: Core.FileConfig.cid
        };
        var tids = [];
        var cids = [];
        for(var i = 0, len = arr.length; i < len; i++){
            var item = arr[i];
            if(item.attr("file_type") == "1"){
                tids.push(item.attr("file_id"));
            }
            else if(item.attr("file_type") == "0"){
                cids.push(item.attr("cate_id"));
            }
        }
        if(tids.length){
            data.tid = tids.join(",");
        }
        if(cids.length){
            data.cid = cids.join(",");
        }
        return data;
    }
    
    //显示按钮逻辑判断
    var isType = function(arr){
        var result = {}, file_type , item;
        if(Core.FileConfig.aid == 7){
            if(arr.length){
                result["rbfile"] = true;
            }
            result["rb"] = true;
            return result;
        }
        else if(Core.FileConfig.aid == 22){
            if(arr.length){
                result["syncfile"] = true;
            }
            result["sync"] = true;
            return result;
        }
        if(Core.FileConfig.aid == -2 && arr.length){
            result["sentfile"] = true;
            result["expfile"] = true;
            return result;
        }
        if(Core.FileConfig.aid == 0){
            result["onekey"] = true;
        }
        else{
            result["onekey"] = false;
			
        }
        if(arr.length == 1){
            //选择了一条记录
            item = arr[0];
            file_type = item.attr("file_type");
            if(file_type == "1"){
                //选中单个文件
                if(_cache.aid.toString() == "3"){
                    result["onephoto"] = true;
                }
                else if(_cache.aid.toString() == "4"){
                    result["onemusic"] = true;
                }
                else if(_cache.aid.toString() == "2"){
                    result["onedocument"] = true;
                }
                else if(_cache.aid.toString() == "9"){
                    result["onemovie"] = true;
                }
                else{
                    result["onefile"] = true;
                }
                if(Core.FileConfig.aid != 3 && Core.FileConfig.aid != 4 && Core.FileConfig.aid != 9){
                    if(item.attr("is_share") == "1"){
                        result["share"] = true;
                        if(Core.FilePermission.Vip()){
                            result["sharefile"] = true;
                        }
                        result["renew"] = true;
                    }
                    else{
                        result["cancelshare"] = true;
                    }
                    result["lock"] = true;
                }
                
            }
            else if(file_type == "0"){
                //选中单个文件夹
                result["onefolder"] = true;
                result["movefolder"] = true;
                if(Core.FileConfig.aid != 3 && Core.FileConfig.aid != 4 && Core.FileConfig.aid != 9){
                    if(Core.FilePermission.SharedDir(Core.FileConfig.aid)){
                        if(item.attr("is_share") == "1"){
                            result["onesharefolder"] = true;
                        }
                        if(item.attr("is_share") == "1"){
                            result["share"] = true;
                        }
                        else{
                            result["cancelshare"] = true;
                        }
                    }
                }
                
                if(_cache.aid.toString() == "3" || _cache.aid.toString() == "4"){
                    
                    result["onefoldercover"] = true;
                }
                else{
                    result["lock"] = true;
                }
            }
        }
        else{
            //选择了多条文件
            var fileCount = 0, folderCount = 0, shareCount = 0;
            for(var i = 0, len = arr.length; i < len; i++){
                item = arr[i];
                file_type = item.attr("file_type");
                if(file_type == "1"){
                    fileCount++;
                }
                else if(file_type == "0"){
                    folderCount++;
                }
                if(item.attr("is_share") == "1"){
                    shareCount++;
                }
            }
            if(fileCount && folderCount){
                result["fewfandfl"] = true;
                if(Core.FilePermission.Shared(Core.FileConfig.aid) && Core.FilePermission.SharedDir(Core.FileConfig.aid)){
                    if(shareCount == arr.length){
                        result["share"] = true;
                        result["renew"] = true;
                    }
                    else{
                        result["cancelshare"] = true;
                        if(shareCount){
                            result["share"] = true;
                        }
                    }
                    
                }
            }
            else if(fileCount && !folderCount){
				
                if(_cache.aid.toString() == "3"){
                    result["fewphoto"] = true;
                }
                else if(_cache.aid.toString() == "4"){
                    result["fewmusic"] = true;
                }
                else if(_cache.aid.toString() == "9"){
                    result["fewmovie"] = true;
                }
                else{
                    result["fewfile"] = true;
                }
                if(Core.FileConfig.aid != 3 && Core.FileConfig.aid != 4 && Core.FileConfig.aid != 9){
                    if(shareCount == arr.length){
                        result["share"] = true;
                        if(Core.FilePermission.Vip()){
                            result["sharefile"] = true;
                        }
                        result["renew"] = true;
                    }
                    else{
                        result["cancelshare"] = true;
                        if(shareCount){
                            result["share"] = true;
                        }
                    }
                }
            }
            else if(!fileCount && folderCount){
                result["fewfolder"] = true;
                if(Core.FileConfig.aid != 3 && Core.FileConfig.aid != 4 && Core.FileConfig.aid != 9){
                    if(Core.FilePermission.SharedDir(Core.FileConfig.aid)){
                        if(shareCount == arr.length){
                            result["share"] = true;
                        }
                        else{
                            result["cancelshare"] = true;
                            if(shareCount){
                                result["share"] = true;
                            }
                        }
                    }
                }
            }
        }
        
        return result;
    }
    
    var buttonAction = {
        del: function(list){
            var delcon = false;
            
            delcon = "删除后文件或文件夹会移至回收站暂时不会被永久删除，您可以到回收站来永久删除或还原这些文件。";
            if(Core.FileConfig.aid == 0){
                delcon = "";
            }
            Core.Message.Confirm({
                type: "war", 
                text: "确认要删除选中的文件吗？",
                content: delcon, 
                win:_cache.win, 
                callback: function(r){
                    if(r){
                        //Core.MinMessage.Show({text:" 成功删除了" + _cache.dataList.length + "个文件", type:"suc", timeout:Core.CONFIG.MsgTimeout, window:_cache.win});
                        var url = PAGE_PATHS["MY"]+"/index.php?r=operate/index&ct=file&ac=delete";
                        var data = getSelFilesData(list);
                        $.ajax({
                            url: url,
                            type: "POST",
                            data: data,
                            dataType: "json",
                            success: function(r){
                                var arr = list;
                                var dellist = [];
                                if(r.state){
                                    dellist = arr;
                                }
                                else{
                                    for(var i = 0, len = arr.length; i < len; i++){
                                        var item = arr[i]
                                        if(item.attr("file_type") == "1" && r['data']['f']){
                                            dellist.push(item);
                                        }
                                        else if(item.attr("file_type") == "0" && r['data']['c']){
                                            dellist.push(item);
                                        }
                                    }
                                }
                                for(var i = 0, len = dellist.length; i < len; i++){
                                    var item = dellist[i];
                                    if(item.attr("file_type") == "0"){
                                        //删除目录树DOM
                                        Core.Tree.DeleteNode(item.attr("cate_id"));
                                    }
                                }

                                if(dellist.length){
                                    Core.MinMessage.Show({
                                        text: "删除成功", 
                                        timeout: Core.CONFIG.MsgTimeout, 
                                        window:_cache.win, 
                                        type:"suc"
                                    });
                                    if(Core.FileConfig.DataAPI) Core.FileConfig.DataAPI.Del(Core.FileConfig.aid, Core.FileConfig.cid, dellist);

                                    if(Core.FileConfig.aid != 0){
                                        Core.CountSync.Sync();
                                    }
                                    else{
                                        Core.SpaceData.Sync();
                                    }
                                }
                                else{
                                    Core.MinMessage.Show({
                                        text: "删除失败", 
                                        timeout: Core.CONFIG.MsgTimeout, 
                                        window:_cache.win, 
                                        type:"err"
                                    });
                                }
                            }
                        })
                    }
                }
            }); 
        },
        share: function(list, btnType){
            if(btnType == "share"){
                Core.SendFileDG.Open(list, "file");
            }
            else{
                buttonAction.share_dataaccess(list, btnType);
            }
        },
        share_dataaccess: function(list, btnType, sharecallback){
            var url = "?ct=file&ac=share";
            var data = getSelFilesData(list);
            data.is_share = 1;
            var msg = "分享";
            switch(btnType){
                case "cancelshare":
                    data.is_share = 0;
                    msg = "取消分享";
                    break;
                case "renew":
                    data.is_share = 2;
                    msg = "续期";
                    break;
            }
            $.ajax({
                url: url,
                type: "POST",
                data: data,
                dataType: "json",
                success: function(r){
                    var arr = list;
                    var dellist = [];
                    if(r.state){
                        dellist = arr;
                    }
                    else{
                        for(var i = 0, len = arr.length; i < len; i++){
                            var item = arr[i]
                            if(item.attr("file_type") == "1" && r['data']['f']["state"]){
                                dellist.push(item);
                            }
                            else if(item.attr("file_type") == "0" && r['data']['c']["state"]){
                                dellist.push(item);
                            }
                        }
                    }

                    for(var i = 0, len = dellist.length; i < len; i++){
                        var item = dellist[i];
                        if(item.attr("file_type") == "0"){
                            //改变目录树图标
                            Core.Tree.SharedNode(item.attr("cate_id"), data.is_share);
                        }
                    }

                    if(dellist.length){
                        if(r["state"] && btnType == "share"){
                            for(var i = 0, len = list.length; i < len; i++){
                                var item = list[i];
                                if(item.attr("file_type") == "0"){
                                    var dc = item.attr("cate_id");
                                    if(r.dir_pickcode[dc]){
                                        item.attr("pick_code", r.dir_pickcode[dc]);
                                    }
                                }
                            }
                            if(sharecallback) sharecallback();
                        }
                        else{
                            Core.MinMessage.Show({
                                text: msg + "成功", 
                                timeout: Core.CONFIG.MsgTimeout, 
                                window:_cache.win, 
                                type:"suc"
                            });
                        }
                        if(Core.FileConfig.DataAPI) Core.FileConfig.DataAPI.Share(Core.FileConfig.aid, Core.FileConfig.cid, data.is_share, dellist);
                    }
                    
                    if(!r["state"] && r['data']){
                        if(r['data']['f']){
                            Core.MinMessage.Show({
                                text: r['data']['f']["message"], 
                                timeout: Core.CONFIG.MsgTimeout, 
                                window:_cache.win, 
                                type:"err"
                            });
                            return false;
                        }
                        else if(r['data']['c']){
                            Core.MinMessage.Show({
                                text: r['data']['c']["message"], 
                                timeout: Core.CONFIG.MsgTimeout, 
                                window:_cache.win, 
                                type:"err"
                            });
                            return false;
                        }
                        else{
                            if(r.msg_code == "200100"){
                                Core.Message.Confirm({
                                    text: r.msg,
                                    confirm_text: "立即完成",
                                    type: "war",
                                    callback: function(res){
                                        if(res){
                                            window.setTimeout(function(){
                                            PageFrameCtl.NewUser();
                                            },10);
                                            
                                        }
                                    }
                                })
                            }
                            else{
                                Core.MinMessage.Show({
                                    // text: msg + "失败", 
                                    text: r.msg,
                                    timeout: Core.CONFIG.MsgTimeout, 
                                    window:_cache.win, 
                                    type:"err"
                                });
                            }
                        }
                    }
                }
            })	
        },
        send: function(list){
            if(list && list.length == 1){
                var item = list[0];
                if(item.attr("file_type") == "0" && !Core.FilePermission.Vip()){
                    Core.VIPNotice.Upgrade();
                    return;
                }
            }
            Core.SendFileDG.Open(list, "friend");
        }
    }
    
    var doEvent = function(btnType){
        var cRes = Core.FileMenu.CheckButtonIsDo(_cache.dataList, btnType);
        if(!cRes){
            return false;
        }
        else{
            if(typeof cRes == "object"){
                _cache.dataList = cRes;
            }
        }
        switch(btnType){
            //删除文件或文件夹
            case "delete":
                buttonAction.del(_cache.dataList);
                break;
            case "move":
                if(_cache.dataList && _cache.dataList.length == 1){
                    var item = _cache.dataList[0];
                    if(item.attr("file_type") == "0" && !Core.FilePermission.Vip()){
                        Core.VIPNotice.Upgrade();
                        return;
                    }
                }
                var isMoveFolder = false;
                if(_cache.dataList.length && _cache.dataList[0].attr("file_type") == "0"){
                    isMoveFolder = true;
                }
                if(isMoveFolder){
                    Core.TreeDG.Show({
                        list: _cache.dataList, 
                        win:_cache.win, 
                        type: "move_folder"
                    });
                }
                else{
                    Core.TreeDG.Show({
                        list: _cache.dataList, 
                        win:_cache.win, 
                        type: "move"
                    });
                }
                break;
            case "copy":
                Core.TreeDG.Show({
                    list: _cache.dataList, 
                    win:_cache.win, 
                    type:"copy"
                });
                break;
            case "edit_name":
                if(_cache.dataList && _cache.dataList.length){
                    var node = _cache.dataList[0];
                    if(node.attr("file_type") == "1"){
                        Core.FileReNameDG.Show(node.attr("file_id"), node.find('[field="file_name"]').attr("title"));
                    }
                    else{
                        var cid = node.attr("cate_id");
                        Core.Dir.Rename(Core.FileConfig.aid, cid);
                    }
                }
                break;
            case "cover":
                if(_cache.dataList && _cache.dataList.length){
                    var cid = _cache.dataList[0].attr("cate_id");
                    Core.FileSelectDG.EditCover(Core.FileConfig.aid, cid);
                }
                break;
            case "shareto":
                
                var sharelist = {"weibo":1, "q":1, "share":1, "send":1};
                var openCondition = {};
                var res = Core.FileMenu.CheckType(Core.FileConfig.aid, Core.FileConfig.cid, _cache.dataList);
                if(res){
                   for(var i = 0, len = res.length; i < len; i++){
                       if(sharelist[res[i]]){
                           openCondition[res[i]] = 1;
                       }
                   }
                }
               
                Core.FileAPI.ShareTO(_cache.dataList, openCondition);
                break;
            case "share":
            case "cancelshare":
            case "renew":
                buttonAction.share(_cache.dataList,btnType);
                break;
            case "play":
                var addList = [];
                for(var i = 0, len = _cache.dataList.length; i < len; i++){
                    var item = _cache.dataList[i];
                    addList.push({
                        name: item.find('[field="file_name"]').attr("title"), 
                        mp3: item.attr("path")
                    });
                }
                Core.MusicPlayer.Add(addList);
                break;
            case "view":
                var start = _cache.list[0].attr('s');
                var limit = _cache.list[0].attr('limit');
                var ids   = _cache.list[0].attr('ids');
                //预览图片
                Core.PhotoView.Show(Core.FileConfig.aid, Core.FileConfig.cid, _cache.dataList[0].attr("file_id"), _cache.dataList[0].attr("is_online"), start, limit, ids);
                break;
            case "exp_delete":
                //移除收件与发件记录
                Core.FileAjax.DeleteExpMsg(Core.FileConfig.cid, _cache.dataList, _cache.win);
                break;
            case "exp_recv":
                //接收文件
                Core.FileAPI.RecvExp(_cache.dataList, _cache.win);
                break;
            case "restore":
                //还原文件
                var tids = [];
                for(var i = 0, len = _cache.dataList.length; i < len; i++){
                    var item = _cache.dataList[i];
                    tids.push(item.attr("tid"));
                }
                Core.FileAjax.RestoreRB(tids, _cache.win);
                break;
            case "rb_delete":
                //删除回收站文件
                var tids = [];
                for(var i = 0, len = _cache.dataList.length; i < len; i++){
                    var item = _cache.dataList[i];
                    tids.push(item.attr("tid"));
                }
                Core.FileAjax.DeleteRB(tids, _cache.win);
                break;
            case "send":
                //发送文件
                buttonAction.send(_cache.dataList);
                break;
            case "download":
                
                if(_cache.dataList.length){
                    if(_cache.dataList.length == 1){
                        Core.FileAPI.Download($(_cache.dataList[0]).attr("pick_code"),_cache.win);
                    }
                    else{
                        Core.FileAPI.UDownDownload(_cache.dataList);
                    }
                }
                break;
            case "copylink":
                var str = Core.FileAPI.GetCopyText(_cache.dataList);
                Util.Copy(str);
                break;
            case "edit":
                if(_cache.dataList && _cache.dataList.length){
                    var item = _cache.dataList[0];
                    Core.FileDescDG.Show({
                        aid: Core.FileConfig.aid, 
                        file_id: item.attr("file_id"), 
                        title: item.find('[field="file_name"]').attr("title"), 
                        value: item.find("[field='desc']").val()
                    });
                }
                break;
            case "sync_delete":
                if(_cache.dataList && _cache.dataList.length){
                    if(Core.FileConfig.DataAPI && Core.FileConfig.DataAPI.DeleteSync){
                        Core.Message.Confirm({
                            text: '确认要删除选中的文件或文件夹吗？', 
                            type: "war", 
                            callback: function(r){
                                if(r){
                                    Core.FileConfig.DataAPI.DeleteSync(_cache.dataList);
                                }
                            }
                        })
                    }
                     
                }
                break;
            case "read":
                //预览图片
                Core.Reader.Open(_cache.dataList[0].attr("pick_code"));
                break;
            case "privacy":
                Core.PrivacyDG.File(_cache.dataList[0]);
                break;
            case "unloading":
                Core.FileAjax.AllowCollect(_cache.dataList,1);
                break;
            case "cancelunloading":
                Core.FileAjax.AllowCollect(_cache.dataList,0);
                break;
            case "weibo":
                Core.SendFileDG.Open(_cache.dataList, "weibo");
                break;
            case "q":
                Core.SendFileDG.Open(_cache.dataList, "q");
                break;
            default:
                Core.MinMessage.Show({
                    text:" 操作数量:" + _cache.dataList.length, 
                    type:"suc", 
                    timeout:Core.CONFIG.MsgTimeout, 
                    window:_cache.win
                });
                break;
        }
    }
    
    var hideRightMenu = function(){
        if(_cache.right_file){
            _cache.right_file.find("[val]").hide();
            _cache.right_file.hide();
        }
        if(_cache.right_cate){
            _cache.right_cate.find("[val]").hide();
            _cache.right_cate.hide();
        }
    }
    
    return {
        CheckButtonIsDo: function(list, type){
            if(type != "delete" && type != "upload" && type != "adddir"){
                if(list.length == 1){
                    if(list[0].attr("file_status") == "0"){
                        Core.MinMessage.Show({text: "文件需续传完成后再操作。", type: "war", timeout: Core.CONFIG.MsgTimeout});
                        return false;
                    }
                }
                else if(list.length > 1){
                    var arr = [], isReupload = false;

                    for(var i = 0, len = list.length; i < len; i++){
                        var node = list[i];
                        if(node.attr("file_status") == "0"){
                            isReupload = true;
                            continue;
                        }
                        arr.push(node);
                    }
                    if(arr.length == 0){
                        if(isReupload){
                            Core.MinMessage.Show({text: "文件需续传完成后再操作。", type: "war", timeout: Core.CONFIG.MsgTimeout});
                        }
                        return false;
                    }
                    else{
                        return arr;
                    }
                }
            }
            return true;
        },
        CheckType: function(aid, cid, arr){
            _cache.aid = aid;
            _cache.cid = cid;
            var result = [];
            var r = isType(arr);
            for(var k in r){
                if(r[k]){
                    var ablelist = _cache.setting[k];
                    for(var i = 0, len = ablelist.length; i < len; i++){
                        result.push(ablelist[i]);
                    }
                }
            }
            return result;
        },
        GetSetting: function(){
            return _cache.setting;
        },
        Action: function(type){
            return buttonAction[type];
        },
        DoEvent: function(arr, btnType){
            _cache.dataList = arr;
            doEvent(btnType);
        },
        FileRight: function(aid, cid, arr, x, y){
            _cache.aid = aid;
            _cache.cid = cid;
            _cache.dataList = arr;
            if(arr && arr.length){
                if(!_cache.right_file){
                    _cache.right_file = Core.FloatMenu.Show("right_file");
                    _cache.right_file.find("[val]").each(function(i){
                        if(!_cache.right_btn_list){
                            _cache.right_btn_list = {};
                        }
                        _cache.right_btn_list[$(this).attr("val")] = $(this);
                        $(this).bind("click", function(e){
                            Core.Html.StopPropagation(e);
                            var btnType = $(this).attr("val");
                            if($(this).find(".arrow").length){
                                return false;
                            }
                            doEvent(btnType);
                            hideopbox();
                            hideRightMenu();
                            return false;
                        })
                    });
                }
                
                var showCout = {};
                var count = 0;
                if(_cache.right_btn_list){
                    for(var k in _cache.right_btn_list){
                        _cache.right_btn_list[k].hide();
                    }
                    var r = isType(arr);
                    var specilobj = _cache.specil[_cache.aid];
                    
                    for(var k in r){
                        if(r[k]){
                            var ablelist = _cache.setting[k];
                            if(specilobj){
                                for(var i = 0, len = ablelist.length; i < len; i++){
                                    if(specilobj[ablelist[i]] && _cache.right_btn_list[ablelist[i]]){
                                        _cache.right_btn_list[ablelist[i]].show();
                                    }
                                }    
                            }
                            else{
                                for(var i = 0, len = ablelist.length; i < len; i++){

                                    if(_cache.right_btn_list[ablelist[i]]){
                                        _cache.right_btn_list[ablelist[i]].show();
                                    }
                                }
                            }
                        }
                    }
                    
                }
                
                var l = x, t = y;
                t += _main_top;
                l += _main_left;
                showopbox(function(){
                    hideRightMenu();
                });
                Core.FloatMenu.SetRightBtnPos(_cache.right_file, "right_file", l, t);
            }
        },
        FolderRight: function(aid, cid, x, y){
            _cache.dirAid = aid;
            _cache.dirCid = cid;
            //权限判断
            var node = Core.Tree.GetItem(cid);
            if(cid.toString().indexOf("_") != -1){
                cid = 0;
            }
            var aid = node.aid;
            var pid = node.pid;
            if(pid != undefined){
                if(pid.toString().indexOf("_0") != -1){
                    pid = 0;
                }
            }
            else{
                pid = "";
            }
            var isshare = Number(node.is_share);

            var showState = true;
            
            var hideList = [];
            if(cid == 0){
                hideList.push("share");
                hideList.push("cancelshare");
                hideList.push("edit");
                hideList.push("delete");
                hideList.push("cover");
                hideList.push("privacy");
                hideList.push("move");
            }
            else{
                if(!Core.FilePermission.Vip()){
                    hideList.push("move");
                }
            }
            switch(Number(aid)){
                case 0:
                case -2:
                case 7:
                case 21:
                case 22:
                    showState = false;
                    break;
                case 1:
                case 2:
                case 9:
                    if(Number(cid) != 0){
                        if(!Core.FilePermission.SharedDir(aid)){
                            hideList.push("share");
                            hideList.push("cancelshare");
                        }
                        else{
                            hideList.push( (isshare?"share":"cancelshare") );
                        }
                    }
                    hideList.push("cover");
                    break;
                case 3:
                case 4:
                    hideList.push("share");
                    hideList.push("cancelshare");
                    hideList.push("privacy");
                    break;
            }
            if(!showState){
                return;
            }
            
            if(!_cache.right_cate){
                _cache.right_cate = Core.FloatMenu.Show("right_cate");
                _cache.right_cate.find("[val]").each(function(i){
                    if(!_cache.right_cate_list){
                        _cache.right_cate_list = {};
                    }
                    _cache.right_cate_list[$(this).attr("val")] = $(this);
                    $(this).bind("click", function(e){
                        Core.Html.StopPropagation(e); 
                        var btnType = $(this).attr("val");
                        //处理事件
                        switch(btnType){
                            
                            case "add": //新建文件夹
                                Core.Dir.Create(_cache.dirAid, _cache.dirCid);
                                break;
                            case "share":   //共享文件夹
                                Core.Dir.Shared(_cache.dirAid, _cache.dirCid, 1);
                                break;
                            case "cancelshare": //取消共享
                                Core.Dir.Shared(_cache.dirAid, _cache.dirCid, 0);
                                break;
                            case "edit":    //重命名文件夹
                                Core.Dir.Rename(_cache.dirAid, _cache.dirCid);
                                break;
                            case "move":
                                Core.TreeDG.Show({
                                    list: [$('<div area_id="'+_cache.dirAid+'" cate_id="'+_cache.dirCid+'"></div>')], 
                                    win:_cache.win, 
                                    type: "move_folder"
                                });
                                break;
                            case "delete":  //删除文件夹
                                Core.Dir.Delete(_cache.dirAid, _cache.dirCid);
                                break;
                            case "cover":
                                Core.FileSelectDG.EditCover(_cache.dirAid, _cache.dirCid);
                                break;
                            case "privacy":
                                Core.PrivacyDG.Folder(_cache.dirAid, _cache.dirCid);
                                break;
                        }
                        hideopbox();
                        hideRightMenu();
                        return false;
                    })
                });
            }
            
            _cache.right_cate.find("[val]").show();
            for(var i = 0, len = hideList.length; i < len; i++){
                _cache.right_cate.find("[val='" + hideList[i] + "']").hide();
            }
            
            var l = x, t = y;
            t += _main_top;
            showopbox(function(){
                hideRightMenu();
            });
            Core.FloatMenu.SetRightBtnPos(_cache.right_cate, "right_cate", l, t);
        }
    }
})();

/*
	上传文件控制类
*/
Core.Upload = (function(){
    var _cache = {
        aid: 1, 
        cid: 0, 
        ActiveAid:1, 
        ActiveCid:0	//上传目录
    }

    //小进度框
    var _MinForm = new (function(){
        var _self = this;
        var _content;
		
        var bindEvents = function(){
            _content.unbind("click").bind("click",function(e){
                _MinForm.Close();
                _DisplayForm.Open();
                return false;
            })
        }
		
        var _openState = false;
        this.Open = function(){
            _openState = true;
        }
        this.Close = function(){
            _openState = false;
			if(_content){
				_content.hide();
			}
        }
		
        this.Progress = function(obj){
            //显示进度
            if(!_DisplayForm.IsOpen && obj){
				if(!_content){
					_content = $('<div class="upload-min" style="display:none; bottom:auto;z-index:99; right:190px; top: 12px;"><i style="width:0;" rel="up_per"></i><span>0&nbsp;&nbsp;10B/s</span></div>');
					$(document.body).append(_content);
					bindEvents();
				}
				
                var size = 0;
                var count = 0;
                var complete = 0;
                for(var k in obj){
                    count++;
                    size += Number(obj[k].size);
                    complete += Number(obj[k].complete);
                }
                var per = (complete/size);

                if(!_openState){
                    _self.Open();
					_content.show();
                }
				
                _content.find('[rel="up_per"]').css({
                    "width":((per*100) + "%")
                });
				_content.find("span").html((per*100).toFixed(2) + "%" + "&nbsp;&nbsp;("+count+")");
            }
            else{
                if(_openState){
                    _self.Close();
                }
            }
        }
		
    })();
	
    //上传展示窗口
    var _DisplayForm = new (function(){
        var _self = this, _datalist = {}, _cacheData, _loadState = false, _isClose = true, _tree;
        var _content = $('<div class="upload-box">'+
                            '<div class="directory-tree" rel="tree_box"></div>'+
                            '<div class="upload-handle">'+
                                '<div class="fl" rel="js_up_msg"></div>'+
                                '<div class="btn-add-wrap">'+
                                    '<span id="js_upload_fup_box" style="float:left;overflow:hidden;margin-left:-1px; top:-9999px;"><span id="js_upload_fup_btn"></span></span>'+
                                    '<a href="javascript:;" class="btn-add-act" style="display:none;" id="js_upload_tup_box">添加文件【极速】</a>'+
                                    '<a href="javascript:;" class="btn-add-opt" rel="settings" style="display:none;">选项</a>'+
                                '</div>'+
                            '</div>'+
                            '<div class="upload-list">'+
                                '<dl class="file-list" rel="list">'+
                                    '<dt>'+
                                        '<ul>'+
                                            '<li class="file-name">文件名</li>'+
                                            '<li class="file-operate">操作</li>'+
                                            '<li class="file-size">大小</li>'+
                                            '<li class="file-rate">上传进度</li>'+
                                        '</ul>'+
                                    '</dt>'+

                                '</dl>'+
                            '</div>'+
                        '</div>'+
                        '<div class="status-bar">'+
                            '<div class="con">'+
                                '<div class="stat-menu stat-left">'+
                                    '<a href="javascript:;" rel="js_create_folder"><span><i class="icon ico-newdir"></i><i>新建文件夹</i></span></a>'+
                                '</div> ' +
                                '<span rel="upload_msg" style="position:absolute; top:0; left: 100px; padding: 1px;"></span>'+
                                '<div class="stat-menu"><a href="javascript:;" class="fr" btn="clear"><span><i class="icon ico-remove"></i><i>清空已完成文件</i></span></a></div>' +
                            '</div>'+
                        '</div>');
		
        var _fileTemp = '<dd file_id="{id}"><ul><li class="file-name"><i class="file-type"></i>{name}</li><li class="file-operate" rel="op"></li><li class="file-size">{size_str}</li><li class="file-rate" rel="pg_text"></li></ul></dd>';
        var _progressTemp = '<div class="rate-box" rel="pg_box"><i style="width:0;" rel="pg_line"></i></div>';
		
        Core.WindowBase.call(this,{
            title:'文件上传',
            content:_content,
            width: 800,
            height: 500,
            is_not_resize:true, 
            min_title:'<span>上传文件</span>'
        });
		
        var domlist = _content.find("[rel='list']");
		
        var isExist = function(file){
            var result = false;
            if(_cacheData){
                for(var k in  _cacheData){
                    var item = _cacheData[k];
                    if(item.name == file.name && item.aid == file.aid){
                        if(item.cid != undefined || file.cid != undefined){
                            if(item.cid == file.cid){
                                return true;
                            }
                        }
                        else{
                            return true;
                        }
                    }
                }
            }
            return result;
        }
		
        var getBtn = function(obj){
            var btn = $('<a href="javascript:;" class="opt-icon '+obj.className+'" title="' + obj.text + '">'+obj.text+'</a>')
            if(obj.first){
                var btns = obj.dom.find("[rel='op'] a.opt-icon");
                if(btns.length){
                    $(btns[0]).before(btn);
                }
                else{
                    obj.dom.find("[rel='op']").append(btn);
                }
            }
            else{
                obj.dom.find("[rel='op']").append(btn);
            }
            if(obj.hide){
                btn.hide();
            }
            btn.click(obj.callback);
        }
		
        var showUploadMsg = function(msg){
            _content.find("[rel='js_up_msg']").html(msg);
        }
		
        var selectTree = function(aid, cid){
            if(_tree){
                if(!Number(aid)){
                    aid = 1;
                }
                if(!cid){
                    cid = aid + "_0";
                }
                var a = _tree.find("a[cid='"+cid+"']");
				
                var isOpen = !(a.find("i[rel='open']").hasClass("ino") && a.hasClass("focus"));
                
                _tree.find(".focus").removeClass("focus");
                
				if(isOpen){
                    Core.Tree.OpenChild(cid, [_tree]);
                }
                else{
                    Core.Tree.HideChild(cid, [_tree]);
                }
                a.addClass("focus");
				
                _cache.ActiveAid = aid;
                _cache.ActiveCid = cid;
				
                _FUpload.setting(_cache.ActiveAid,_cache.ActiveCid);
                _TUpload.setting(_cache.ActiveAid,_cache.ActiveCid);
				
                switch(Number(_cache.ActiveAid)){
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                    case 9:
                        var msg = "";
                        Core.Upload.Disable(false);
                        if(!Core.FilePermission.Vip()){
                            msg = '本目录可上传'+Util.File.ShowSize(_cache.config[aid.toString()].upload_size_limit)+'的文件';
                            msg += ', <a href="'+Core.CONFIG.Path.VIP+'/vip/?p=upload" class="btn-upgrade" target="_blank">升级VIP</a> 即可上传<b>2GB</b>超大文件';
                        }
                        else{
                            msg = '本目录支持上传 <b>'+Util.File.ShowSize(_cache.config[aid.toString()].upload_size_limit)+'</b> 单个超大文件';
                        }
                        if(!_TUpload.isInstall() && Core.FilePermission.Vip()){
                            msg += '<b>(需安装极速上传控件)</b>';
                        }
                        showUploadMsg("您可多选文件上传哦");
                        break;
                    default:
                        Core.Upload.Disable(true);
                        break;
                }
				
                var arr = Core.Tree.GetParents(_cache.ActiveCid,true);
                for(var i = arr.length - 1; i >= 0; i--){
                    Core.Tree.OpenChild(arr[i].cid,[_tree]);	//展开父级目录
                }
            }
        }
		
        this.ChangeDir = function(aid, cid){
            selectTree(aid, cid);
        }
		
        this.Initial = function(){
            _isClose = false;
			
            _self.warp.removeClass("window-container").addClass("dialog-box").css({height: ""});
			
            
            _content.find("[btn='clear']").unbind("click").bind("click", function(){
                _content.find("dd[file_id]").each(function(){
                    if(_cacheData && _cacheData[$(this).attr("file_id")]){
                        return;
                    }
                    $(this).empty().remove();
                })
                return false;
            })
			
            /*加载目录树*/
            var treeList = Core.Tree.GetTree();
		
            _tree = _content.find('[rel="tree_box"]');
			
            var parentUL = $("<dl></dl>");
            for(var k in treeList){
                treeList[k].find("[aid='0']").parent().empty().remove();
                treeList[k].find("[aid='5']").parent().empty().remove();
                parentUL.append(treeList[k].clone(true));
            }
            Core.Tree.BindDoms(parentUL);
            _tree.append(parentUL);
            parentUL.find('dd').append("<li title='' style='display: none';><a pid='1_0' aid='' cid='' href='javascript:;' title='' style='padding-left: 35px;' class='focus'><i class='imenu ico-folder'></i><em rel='text'></em></a></li>");
            _tree.find("a[cid]").click(function(){
                var ele = $(this);
                selectTree(ele.attr("aid"), ele.attr("cid"));
                return false;
            })
            /*********/
			
            /*载入Flash上传*/
            _FUpload.dom("js_upload_fup_btn", "js_upload_fup_box");
            _FUpload.setting(_cache.ActiveAid, _cache.ActiveCid);
            _FUpload.show();
            /*************/
			
            if(_TUpload.isInstall()){
                _TUpload.bindButton("js_upload_tup_box");
                _TUpload.setting(_cache.ActiveAid, _cache.ActiveCid);
            }
            else{
                _content.find('[rel="js_up_install"]').bind("click", function(){
                    _TUpload.showDownload();
                    return false;
                });
            }
			
            _self.Install();

            var settings_ele = _content.find("[rel='settings']");
			settings_ele.hide();
            if(_TUpload.isInstall()){
                _cache.setting_dom = Core.FloatMenu.Show("up_setting");
                _self.warp.find("[rel='js_hint_msg_box']").empty().remove();
                settings_ele.show();
            }
            else{
                if(!Core.CONFIG.IsWindows){
                    _self.warp.find("[rel='js_hint_msg_box']").empty().remove();
                }
                $("#js_upload_tup_box").empty().remove();
                
            }
			
            //加载设置菜单
            if(_cache.setting_dom){
                Util.DropDown.Bind({
                    Title: settings_ele,
                    Content: _cache.setting_dom,
                    IsOverShow: true,
                    ShowHandler: function(){
                        var ele = settings_ele;
                        var t = ele.offset().top + ele.height();
                        var l = ele.offset().left;
                        Core.FloatMenu.SetRightBtnPos(_cache.setting_dom, "up_setting", l, t, ele.width(), ele.height());		
                    }
                })	//绑定下拉
                var menuList = _cache.setting_dom.find("[val]");
                //绑定事件
                menuList.each(function(i){
                    var item = $(this);
                    var type = item.attr("val");
                    item.click(function(e){
                        switch($(this).attr("val")){
                            case "flash":
                                Core.Setting.Change({
                                    'os_file_upload_type': 0
                                },function(r){
                                    if(r.state){
                                        Core.Upload.ChangeEngine(0);
                                        checkUpEngine();
                                    }
                                })
                                break;
                            case "ocx1":
                                Core.Setting.Change({
                                    'os_file_upload_type': 1
                                },function(r){
                                    if(r.state){
                                        Core.Upload.ChangeEngine(1);
                                        Core.CONFIG.TUpSp = "0";
                                        checkUpEngine();
                                    }
                                })
                                break;
                            case "ocx2":
                                Core.Setting.Change({
                                    'os_file_upload_type': 2
                                },function(r){
                                    if(r.state){
                                        Core.Upload.ChangeEngine(1);
                                        Core.CONFIG.TUpSp = "1";
                                        checkUpEngine();
                                    }
                                })
                                break;
                        }
                        return false;
                    })
                });
            }
			
            listen();
            selectTree(_cache.ActiveAid, _cache.ActiveCid);
            
            //New Folder Button
            _content.find("[rel='js_create_folder']").bind("click", function(){
                var addCid = _cache.ActiveCid.toString().indexOf("_0") != -1? 0: _cache.ActiveCid;
                var addAid = Number(_cache.ActiveAid);
                
                Core.Tree.CreateFolder(addAid, addCid, function(r){
                    selectTree(r.aid, r.cid.toString());
                    Core.Dir.DoHandler("AddNode", r);
                }, _self);
                return false;
            })
            
            _loadState = true;
        }
		
        //改变上传模式
        var checkUpEngine = function(){
            if(_cache.setting_dom){
                var updom = _cache.setting_dom;
                updom.find("i.ico-done").removeClass("icon").removeClass("ico-done");
				
                switch(Core.CONFIG.UpEngine){
                    case 0:
                        updom.find("[val='flash'] i").addClass("icon").addClass("ico-done");
                        break;
                    case 1:
                        if(Number(Core.CONFIG.TUpSp) == 1){
                            updom.find("[val='ocx2'] i").addClass("icon").addClass("ico-done");
                        }
                        else{
                            updom.find("[val='ocx1'] i").addClass("icon").addClass("ico-done");
                        }
                        break;
                }
                _cache.setting_dom.hide();
            }
        }
		
        this.Install = function(){
            if(Core.CONFIG.UpEngine && _TUpload.isInstall()){
                _FUpload.hide();
                _TUpload.show((Core.CONFIG.TUpSp == "0")?"添加文件【电信极速】" : "添加文件【联通极速】");
            }
            else{
                //Flash上传
                _FUpload.show();
                _TUpload.hide();
            }
        }
		
        this.Add = function(file){
            if(!isExist(file)){
                file.size_str = Util.File.ShowSize(file.size);
                var temp = $(String.formatmodel(_fileTemp,file));
				 
                if(file.up_type == 1){
                    //增加按钮(断点续传)
                    getBtn({
                        dom: temp, 
                        text:"暂停", 
                        className:"opt-pause",
                        callback: function(e){
                            if(file.status.toString() != "4" || file.status.toString() != "70"){
                                if(_TUpload.pause(file)){
                                    _self.ShowMessage(file.id,"暂停",0);
                                    var dom = domlist.find("[file_id='"+file.id+"']");
                                    dom.find(".opt-pause").hide();
                                    dom.find(".opt-continue").css({
                                        display:""
                                    });
                                }
                            }
                            return false;	
                        }
                    });
                    //continue
                    getBtn({
                        dom: temp, 
                        text:"继续", 
                        hide: true, 
                        className:"opt-continue",
                        callback: function(e){
                            if(_TUpload.reupload(file)){
                                _self.ShowMessage(file.id,"准备续传..",0);
                                var dom = domlist.find("[file_id='"+file.id+"']");
                                dom.find(".opt-pause").css({
                                    display:""
                                });
                                dom.find(".opt-continue").hide();
                            }
                            return false;	
                        }
                    });
                    getBtn({
                        dom: temp, 
                        text:"移除", 
                        className:"opt-delete",
                        callback: function(e){
                            if(file.status == undefined || file.status.toString() == "9"){
                                _self.Del(file);
                                _TUpload.del(file);
                            }
                            else{
                                Core.Message.Confirm({
                                    text: "确认要取消上传该文件吗?",
                                    type: "war",
                                    callback: function(r){
                                        if(r){
                                            _self.Del(file);
                                            _TUpload.del(file);
                                        }
                                    }
                                })
                            }
                            return false;	
                        }
                    });
                }
                else{
                    //增加按钮(Flash上传)
                    getBtn({
                        dom: temp, 
                        text:"移除", 
                        className:"opt-delete",
                        callback: function(e){
                            _self.Del(file);
                            var access = _FUpload.getAccess();
                            access.del(file);
                            return false;	
                        }
                    });
                }
				 
                domlist.append(temp);
                if(file.error){
                    _self.Error(file);
                }
                else{
                    if(!_cacheData){
                        _cacheData = {};
                    }
                    _cacheData[file.id] = file;
                }
            }
        }
		
        this.HideCTLButton = function(file, pause, conti){
            if(file.up_type == 1){
                var dom = domlist.find("[file_id='"+file.id+"']");
                if(dom.length){
                    var pauseBtn = dom.find(".opt-pause");
                    var contiBtn = dom.find(".opt-continue");
                    if(pause){
                        if(pauseBtn.css("display") != "none"){
                            pauseBtn.hide();
                        }
                    }
                    else{
                        if(pauseBtn.css("display") == "none"){
                            pauseBtn.css({
                                display:""
                            });
                        }
                    }
                    if(conti){
                        if(contiBtn.css("display") != "none"){
                            contiBtn.hide();
                        }
                    }
                    else{
                        if(contiBtn.css("display") == "none"){
                            contiBtn.css({
                                display:""
                            });
                        }
                    }
                }
            }
        }
		
        this.Del = function(file){
            //if(isExist(file)){
            var dom = domlist.find("[file_id='"+file.id+"']");
            if(dom.length){
                dom.html("").remove();
            }
            if(_cacheData){
                _cacheData[file.id] = null;
                delete _cacheData[file.id];
            }
        //}
        }
		
        this.Get = function(id){
            return _cacheData[id];
        }
		
        this.IsExist = function(file){
            return isExist(file);
        }
		
        this.Success = function(file){
            var dom = domlist.find("[file_id='"+file.id+"']");
            dom.find("[rel='pg_text']").html('<i class="icon ico-done"></i>');
            dom.find('.rate-box').html("").remove();
            if(file.aid != undefined){
                getBtn({
                    dom: dom, 
                    text:"跳到所在目录", 
                    first:true, 
                    className:"opt-folder",
                    callback: function(e){

                        URL_CTL.GOTO(file.aid, file.cid);
                        _self.Close();
                        return false;
                    }
                });
            }
            if(file.up_type == 1){
                dom.find(".opt-pause").empty().remove();
                dom.find(".opt-continue").empty().remove();
            }
            //上传成功改变数据方法
            if(_cacheData && _cacheData[file.id]){
                _cacheData[file.id] = null
                delete _cacheData[file.id];
            }
        }
		
        //错误
        this.Error = function(file){
            var dom = domlist.find("[file_id='"+file.id+"']");
            dom.attr("class","err");
            dom.attr("title",file.error);
            dom.find("[rel='pg_text']").html("<span>" + file.error + "</span>");
            dom.find('.rate-box').html("").remove();
            dom.find('.opt-pause').empty().remove();
            dom.find('.opt-continue').empty().remove();
            if(_cacheData && _cacheData[file.id]){
                _cacheData[file.id] = null
                delete _cacheData[file.id];
            }
           
        }
		
        this.ShowMessage = function(id, str){
            var dom = domlist.find("[file_id='"+id+"']");
            dom.find("[rel='pg_text']").html(str);
        }
		
        this.Progress = function(file){
            var dom = domlist.find("[file_id='"+file.id+"']");
            if(file.progress == undefined){
                file.progress = '';
            }
            if(file.speed_str == undefined){
                file.speed_str = '';
            }
            dom.find("[rel='pg_text']").html(file.progress + file.speed_str);
            var line = dom.find(".rate-box");
            if(!line.length){
                line = $('<div class="rate-box"><i style="width:0;"></i></div>');
                dom.append(line);
            }
            line.find("i").css({
                width:file.progress
            });
        }

        var _totalobj = null;
        this.TotalProgress = function(){
            if(_cacheData){
                var count = 0;
                var size = 0;
                var complete = 0;
                if(!_totalobj){
                    _totalobj = {};
                }
                var speed = 0;
                for(var k in _cacheData){
                    var file = _cacheData[k];
                    _totalobj[k] = {
                        size: Number(file.size), 
                        complete: file.complete? Number(file.complete):0
                    };
                    if(file.is_uploading == 1){
                        speed += (file.speed ? file.speed : 0);
                    }
                    count++;
                    size += _totalobj[k].size;
                    complete += _totalobj[k].complete;
                }
                //Core.Debug.write(count+" " + size);
                //_totalpersent = complete/size;
                if(count){
                    var per = (complete/size);
                    var less_size = size - complete;
                    var msg = "";
                    var less_time;
                    if(speed){
                        less_time = Util.Date.GetTimeText( Math.floor((less_size / 1024) / speed) );
                    }
                    else{
                        less_time = "00:00:00";
                    }
                    
                    if(count){
                        //msg += count + "个文件正在上传，剩余" + Util.File.ShowSize(size - complete);
                        msg += count + "个文件正在上传，共"+Util.File.ShowSize(size)+"，已完成" + ((per*100).toFixed(1) + "%" + ", 剩余时间: " + less_time);
                    }
                    _content.find('[rel="upload_msg"]').html(msg);
                }
                else{
                    _content.find('[rel="upload_msg"]').html("");
                    _totalobj = null;
                }
            }
            else{
                _totalobj = null;
            }
            _MinForm.Progress(_totalobj);
        }
		
        this.Close = function(){
            _self.Hide();
            Core.WinHistory.Del(_self.Key);
            _self.IsOpen = false;
            _isClose = true;
        }
		
        this.IsOpen = false;
		
        this.Hide = function(){
            var t = _self.warp.offset().top;
            _self.warp.css({
                top: t-9999
            });
            _self.DeActive();
            Core.WinHistory.DeActiveStatus(_self);
            _self.IsActive = false;
            _loadState = false;
			_self.IsOpen = false;
        }
		
        this.Open = function(){
            _self.CreateDom();
			
            checkUpEngine();
			
            if(_loadState){
                _self.warp.show();
            }
            else{
                var t = _self.warp.offset().top;
                _self.warp.css({
                    top: t+9999
                });
                _loadState = true;
            }
			
            if(_isClose){
                _isClose = false;
                Core.WinHistory.Add(_self);
            }
			
            Core.WinHistory.Active(_self);
            _self.IsOpen = true;
        }
		
        this.CheckUpEngine = function(){
            checkUpEngine();
            Core.Upload.ChangeEngine(Core.CONFIG.UpEngine);
        }
		
        this.IsClose = function(){
            return _isClose;
        }
        
        var _reloadTimer;
        this.ReloadPage = function(aid, cid){
            if(_reloadTimer) window.clearTimeout(_reloadTimer);
            _reloadTimer = window.setTimeout(function(){
                if(Core.FileConfig.DataAPI) Core.FileConfig.DataAPI.Reload(aid, cid);
                if(_reloadTimer) window.clearTimeout(_reloadTimer);
            },1200);
        }
    })();
	
    var listen = function(){
        if(!_cache.listenTimer){
            _cache.listenTimer = window.setInterval(function(){
                _DisplayForm.TotalProgress();
            }, 50);
        }
    }

    //控件上传
    var _TUpload = (function(){
        var _TCache = {
            initState: false,
            errorState: false,
            configTxt: "*.*",
            aid: 1,
            cid: 0,
            disable: "btn-disabled",
            FFIndexKey: 0

        }
		
        var _UpList = {}
		
        //解析对象
        var _DataExport = {
            InfoImport: function(file,str){
                //FileName=c:\test.gif&FileSize=123&Progress=89.6&EstimateTime=12&UpStatus=上传&ValidUpBytes=234
                //Core.Debug.write(str);
                if(str){
                    var arr = str.split('|');
                    if(arr.length){
                        for(var i = 0,len = arr.length; i < len; i++){
                            var sArr = arr[i].split("=");
                            switch(sArr[0]){
                                case "FileName":
                                    if(!file.name){
                                        var p = sArr[1].replace(/\//g,"\\");
                                        file.name = p.substring(p.lastIndexOf("\\") + 1,p.length);
                                    }
                                    break;
                                case "TaskID":
                                    file.up_id = sArr[1];
                                    break;
                                case "Progress":
                                    file.progress = sArr[1];
                                    break;
                                case "UpStatus":
                                    file.status = sArr[1];
                                    break;
                                case "EstimateTime":
                                    file.estimate_time = sArr[1];
                                    break;
                                case "ValidUpBytes":
                                    file.valid_up_bytes = sArr[1];
                                    break;
                                case "Speed":
                                    file.speed = sArr[1];
                                    break;
                                case "PickCode":
                                    file.pick_code = sArr[1];
                                    break;
                                case "FilePath":
                                    file.path = sArr[1];
                                    break;
                                //下面是FireFox的返回
                                case "Status":
                                    file.status = sArr[1];
                                    break;
                                case "Total":
                                    file.valid_up_bytes = sArr[1];
                                    file.progress = file.valid_up_bytes + "%";
                                    break;
                                //已上传的毫秒数
                                case "Elapsed":
                                    file.elapsed = sArr[1];
                                    break;
                                case "FileSize":
                                    file.size = Number(sArr[1]);
                                    break;
                                case "ErrCode":
                                    if(_TCache.fferrcode != sArr[1]){
                                        _TCache.fferrcode = sArr[1];
                                        file.err_code = _TCache.fferrcode;
                                        Core.Debug.write("Error: " + file.name + " " + _TCache.fferrcode);
                                    }
                                    break;
                                case "ServerErrCode":
                                    if(_TCache.ffservererrcode != sArr[1]){
                                        _TCache.ffservererrcode = sArr[1];
                                        file.err_server_code = _TCache.ffservererrcode;
                                    }
                                    break;
                                case "ServerErrMsg":
                                    if(_TCache.ffservererrmsg != sArr[1]){
                                        _TCache.ffservererrmsg = sArr[1];
                                        file.err_server_msg = _TCache.ffservererrmsg;
                                    }
                                    break;
                                case "Retry":
                                    file.retry = sArr[1];
                                    break;
                                case "Wait":
                                    file.wait_time = Core.CONFIG.TUpSleepTime - Number(sArr[1]);
                                    break;
                                case "Offset":
                                    file.offset_size = Number(sArr[1]);
                                    break;
                                
                            }
                            if(file.elapsed != undefined && file.status != undefined && file.status.toString() == "6"){
                                file.progress = (Number(file.valid_up_bytes)/ Number(file.size) * 100).toFixed(1) + "%";
                                var offset = file.offset_size;
                                if(!offset){
                                    offset = 0;
                                }
                                file.speed = Number(file.elapsed)?((Number(file.valid_up_bytes) - offset) / 1024) / (Number(file.elapsed)) : 0;
                                
                                file.estimate_time = file.speed?(Number(file.size) - Number(file.valid_up_bytes)) / 1024 / file.speed : 0;
                                file.estimate_time = Util.Date.GetTimeText(file.estimate_time.toFixed(0));
                                
                            }
                        }
                    }
                }
            },
            //组合上传字符
            UploadExport: function(file){
                var str;
                str = 'cookie=' + USER_COOKIE_LB + '&user_id='+USER_ID+'&sha1={sha1}&filesize='+file.size+'&filename='+ encodeURIComponent(file.name) +'&aid='+file.aid+'&cid=' + file.cid + '&pickcode={pick_code}&isp='+Core.CONFIG.TUpSp+'&isweb=1'; 
                
                return str;
            }
        }
		
        var setting = function(config){
            //设置 ActiveX 配置
            _TCache.configTxt = (config.upload_type_limit.length && typeof config.upload_type_limit != 'string')? "*." + config.upload_type_limit.join(";*.") : "*.*";
        }
		
        var _event = {
            ReloadFile: function(file){
                file.is_reupload = true;
                file.upload_status = 0;
				
                file.error = null;
                _UpList[file.id] = file;
				
                _DisplayForm.Add(file);
                _DisplayForm.Open();
                _DisplayForm.HideCTLButton(file,true,false);
            },
            OnReFlashTaskInfo: function(file, taskInfo){
                if(file){
                    _DataExport.InfoImport(file,taskInfo);
					if(!_TCache.DebugStatus || _TCache.DebugStatus != file.status.toString()){
                        _TCache.DebugStatus = file.status.toString();
                        Core.Debug.write("Upload_Status:" + _TCache.DebugStatus);
                    }
                    switch(file.status.toString()){
                        case "1":
                            _DisplayForm.ShowMessage(file.id,"加入成功",0);
                            break;
                        case "等待":
                        case "2":	 // 2、等待 usWait
                            _DisplayForm.ShowMessage(file.id,"等待上传",0);
                            _DisplayForm.HideCTLButton(file,false,true);
                            break;
                        case "计算Hash":
                        case "3":	// 3、计算Hash usCalcHash
                            file.is_uploading = 0;
                            _DisplayForm.ShowMessage(file.id,"解析中:"　+ file.progress,0);
                            if(Number(file.progress.replace("%","")) > 99){
                                _DisplayForm.HideCTLButton(file,false,true);
                            }
                            break;
                        case "请求上传":
                        case "4":	// 4、请求上传 usGetRequest
                            _DisplayForm.ShowMessage(file.id,"正发送上传请求",0);
                            
                            if(file.err_code && file.err_code.toString() == "601"){
                                file.is_uploading = 1;
                                file.speed_str = "(0KB/S)";
                                if(file.progress){
                                    file.complete = file.size * (Number(file.progress.replace("%", ""))/100);
                                }
                                _DisplayForm.Progress(file);
                            }
                            break;
                        case "连接":
                        case "5":	// 5、连接 usConnecting
                            _DisplayForm.ShowMessage(file.id,"连接中...",0);
                            
                            
                            if(file.err_code && file.err_code.toString() == "601"){
                                file.is_uploading = 1;
                                file.speed_str = "(0KB/S)";
                                if(file.progress){
                                    file.complete = file.size * (Number(file.progress.replace("%", ""))/100);
                                }
                                _DisplayForm.Progress(file);
                            }
                            break;
                        case "停止":
                        case "7":	// 7、停止 usStop
                            file.is_uploading = 0;
                            _DisplayForm.ShowMessage(file.id,"暂停",0);
                            _DisplayForm.HideCTLButton(file,true,false);
                            
                            if(Core.CONFIG.TUpDebugKey){
                                if(file.err_code){
                                    if(file.err_code.toString() != "100"){
                                        _DisplayForm.ShowMessage(file.id, file.err_code + " " + file.err_server_code + " " + decodeURIComponent(file.err_server_msg),-1);
                                    }
                                }
                            }
                            break;
                        case "70":
                            if(file.err_server_code && file.err_server_code.toString().length > 3){
                                //删除
                                file.error = decodeURIComponent(file.err_server_msg);
                                _DisplayForm.Error(file);
                                //_TUpload.del(file);
                                return;
                            }
                            if(file.err_code && file.err_code.toString() == "601"){
                                file.is_uploading = 1;
                                file.speed_str = "(0KB/S)";
                                if(file.progress){
                                    file.complete = file.size * (Number(file.progress.replace("%", ""))/100);
                                }
                                _DisplayForm.Progress(file);
                            }
                            else{
                                _DisplayForm.ShowMessage(file.id, "[中断]" + file.wait_time + "秒后重试" ,0);
                            }
                            
                            if(Core.CONFIG.TUpDebugKey){
                                if(file.err_code){
                                    if(file.err_code.toString() != "100"){
                                        
                                        _DisplayForm.ShowMessage(file.id, "重连中 " + file.err_code + " " + file.err_server_code + " " + decodeURIComponent(file.err_server_msg),-1);
                                        
                                    }
                                }
                            }
                            break;
                        case "传输":
                        case "6":	// 6、传输 usTransport
                            file.is_uploading = 1;
                            file.speed_str = "(" + Util.File.ShowSize(file.speed * 1000, 1) + "/S" + ")";
                            file.complete = file.size * (Number(file.progress.replace("%", ""))/100);
                            _DisplayForm.Progress(file);
                            break;
                        case "校验":
                        case "8":	// 8、校验 usCheckSum
                            _DisplayForm.ShowMessage(file.id,"校验文件中...",0);
                            break;
                        case "完成":
                        case "9":	// 9、完成 usComletion
                            file.is_uploading = 0;
                            _DisplayForm.Success(file);
                            var reAid = file.aid;
                            var reCid = file.cid;
                            if(file["pick_code"]){
                                $.ajax({
                                    url: "?ct=upload_ups&ac=set_file_upload_finish",
                                    data: {
                                        "pick_code": file["pick_code"]
                                    },
                                    type: "POST",
                                    success: function(){
                                        Core.SpaceData.Sync();
                                    }
                                })
                            }
                            _TUpload.del(file);
                            try{
                                _DisplayForm.ReloadPage(reAid, reCid);
                                //if(Core.FileConfig.DataAPI) Core.FileConfig.DataAPI.Reload(reAid, reCid);
                            }catch(e){}
							
                            return 2;
                            break;
                    }
                }
            },
            SelectFiles: function(id, fileName, fileSize){
                var p = fileName.replace(/\//g,"\\");
                var file = {
                    id: id,
                    path: fileName,
                    name:  p.substring(p.lastIndexOf("\\") + 1,p.length),
                    size: Number(fileSize),
                    up_type: 1,
                    aid: _TCache.aid,
                    cid: _TCache.cid
                }
                if(_DisplayForm.IsExist(file)){
                    return;
                }
				
                var r = true;
                //判断是否超过限制大小
                var config = _cache.config[file.aid];
                if(config.upload_size_limit < file.size){
                    file.error = String.format(Core.CONFIG.FUpErrMsg["-110"], Util.File.ShowSize(config.upload_size_limit));
                    r = false;
                    Core.Debug.write(config.upload_size_limit + " " + file.size);
                }

                if(file.size <= 0){
                    file.error = "不能上传空文件";
                    r = false;
                }

                //判断是否超出空间大小
                if(r){
                    //验证空间信息
                    var space = Core.SpaceData.GetData();
                    var spaceKey = file.aid;
                    if(Number(spaceKey) > 0 && Number(spaceKey) != 5){
                        spaceKey = 1;
                    }
                    var model = space[spaceKey];
                    if((Number(model.used) + (Number(file.size))) >  Number(model.total)){
                        //file.error = Core.CONFIG.TypeStruct[file.aid.toString()] + "空间大小不足";
                        file.error = "空间大小不足";
                        Core.Debug.write("空间大小不足 Name:" + file.name + " Size:" + file.size + " Space:" + model.total + "\n");
                        r = false;
                    }
                }
				
                if(r){
                    var upStr = _DataExport.UploadExport(file);
                    var uploadId;
                    var addResult = false;

                    var nowDate = new Date();
                    uploadId = Number(nowDate.getHours().toString() + nowDate.getMinutes().toString() + nowDate.getSeconds().toString() + _TCache.FFIndexKey);
                    _TCache.FFIndexKey++;

                    addResult = _TCache.Uploader.AddUpTask(uploadId, file.path,upStr);
					
                    if(uploadId && addResult){
                        file.up_id = uploadId;
                        var str = _TCache.Uploader.GetTaskInfo(file.up_id);
                        Core.Debug.write("返回内容" + str);
                        _DataExport.InfoImport(file,str);
                        _UpList[file.id] = file;	//加入上传列队
                        Core.SpaceData.ChangeUse(file.aid, (Number(file.size)), 1);
                        Core.Debug.write("加入上传列队: Up_ID:" + uploadId + " string:" + upStr);
                    }
                    else{
                        file.error = '加入列队失败';
                        r = false;
                    }
                }
				
                _DisplayForm.Add(file);
                _DisplayForm.Open();
				
                try{
                    if(r){
                        _DisplayForm.ShowMessage(file.id,"准备上传...",0);
                        _TCache.Uploader.ContinueUpTask(file.up_id);
                        Core.Debug.write("开始上传文件: Up_ID:" + file.up_id);
                    }
                }
                catch(e){
                    _DisplayForm.ShowMessage(file.id,"上传出错",-1);
                }
            }
        }
		
        //获取续传列表
        var getFileList = function(){
            var ids = _TCache.Uploader.GetTaskCount();
            for(var i = 0,len = ids; i < len; i++){
                try{
                    var fileStr, ind = 10000;
                    ind = ind + i;
                    fileStr  =_TCache.Uploader.GetTaskInfo(Number(ind));    //ind由10001开始
                    if(!_TCache.ocx_version){
                        _TCache.ocx_version = _TCache.Uploader.GetVersionInfo();
                    }
                    Core.Debug.write(fileStr);
                    if(fileStr){
                        var file = {};
                        var key = new Date().getTime() + "_" + i;
                        file.id = key;
                        file.up_type = 1;	//上传类型
                        _DataExport.InfoImport(file,fileStr);
                        file.up_id = ind;
                        _event.ReloadFile(file);
                    }
                }catch(e){
                    Core.Debug.write(e.message);
                }
            }
            
        }
		
        var loadCab = function(){
            if($.browser.msie){
                $(document.body).append($('<object classid="'+Core.CONFIG.TUpClassID_NB+'" codebase="'+Core.CONFIG.TUpCodeBase_NB+'" id="'+ Core.CONFIG.TUpDomId +'" style=" position:absolute; top:-99999px;" onerror="Core.Upload.TUpLoadError();"></object>'));
            }
        }
		
        var showDownload = function(isupdate){
            loadCab();
			var url;
            var is_unix = false;
            if($.browser.msie){
                url = Core.CONFIG.TUpDownloadUrl_np;
            }
            else{
                if(Core.CONFIG.IsMac){
                    url = Core.CONFIG.TUpDownloadUrl_np_mac;
                }
                else if(Core.CONFIG.IsWindowNT){
                    url = Core.CONFIG.TUpDownloadUrl_np;
                }
                else{
                    //UNIX版本
                    is_unix = true;
                    url = Core.CONFIG.TUpDownloadUrl_np_unix;
                }
            }
            if(is_unix){
                Core.Message.Alert({
                    text: isupdate? "您需要更新大文件上传控件" : "您还未安装大文件上传控件",
                    content: "请点击确定按钮安装，安装完后需重启浏览器。使用上传控件支持最大上传1G的单个文件，并且还提供断点续传功能，方便您随时暂停或恢复上传。<br/>" +
                            '<a href="'+Core.CONFIG.TUpDownloadUrl_np_unix+'">下载64位控件</a> <a href="'+Core.CONFIG.TUpDownloadUrl_np_unix_32+'">下载32位控件</a>',
                    type: "war"
                });
            }
            else{
                Core.Message.Confirm({
                    text: isupdate? "您需要更新大文件上传控件" : "您还未安装大文件上传控件",
                    content: "请点击确定按钮安装，安装完后需重启浏览器。使用上传控件支持最大上传1G的单个文件，并且还提供断点续传功能，方便您随时暂停或恢复上传。",
                    type: "war",
                    confirm_link: url,
                    confirm_text: "立即下载"
                });
            }
        }
		
        var select = function(){
            if($("#" + _TCache.UP_ID).hasClass(_TCache.disable)) return -1;
            //点击上传文件按钮
            if(_TCache.errorState){
                //安装上件控件界面
                showDownload();
            }
            else{
                //'所有支持的类型|*.wma;*.mp1;*.mp2;*.mp3;*.mp4;*.ogg;'
                var configTxt  = "支持的类型|" + _TCache.configTxt;
                try{
                    try{
                        var v = _TCache.Uploader.GetVersionInfo();
                        _TCache.ocx_version = v;
                        var version = Core.CONFIG.TUpUnixVersion;
                        if(Core.CONFIG.IsWindowNT){
                            version = Core.CONFIG.TUpFFVersion;
                        }

                        if(Core.CONFIG.IsMac){
                            version = Core.CONFIG.TUpMacVersion;
                            if(Core.CONFIG.TUpTestVersion[v]){
                                version = v;
                            }
                        }
                        Core.Debug.write("要求版本: " + version + " 控件版本:" + v);
                        if(v.indexOf(version) == -1){
                            Core.MinMessage.Show({
                                text: "您的极速上传控件需要更新才能使用! ",
                                type: "war",
                                timeout: Core.CONFIG.MsgTimeout
                            });
                            showDownload(true);
                            return;
                        }
                    }
                    catch(e){
                    }
                    _TCache.Uploader.SelectFileList(configTxt + "|");
                    return;
                }
                catch(e){
                    showDownload();
                    return;
                }
            }
            return;
        }
		
        var init = function(config){
            if(!_TCache.initState){
                //初始化  绑定事件
                var up = document.getElementById(Core.CONFIG.TUpDomId);
                _TCache.Uploader = up;
                if(_TCache.Uploader){
                    $("#" + _TCache.UP_ID).unbind("click").bind("click", function(){
                        select();
                        return false;
                    })
					
                    //初始化服务
                    _TCache.Uploader.InitService(USER_ID.toString(), USER_COOKIE_LB, Core.CONFIG.TUploadServer, Core.CONFIG.TUpReTryCount, Core.CONFIG.TUpSleepTime);
                    startLinten();	//开启监听
                    window.setTimeout(function(){
                        getFileList(); 	//获取上传列表
                        if(_TUpload.initCallback){
                            _TUpload.initCallback();
                        }
                        _TUpload.initCallback = null;
                    },10);
                    _TCache.initState = true;
                }
            }
            setting(config);
        }
		
        var selectFilesCallback = function(result){
            var arr = result.split("|");
            if(arr.length > Core.CONFIG.TSelectCount){
                Core.MinMessage.Show({
                    text:"每次选择文件不能超过" + Core.CONFIG.TSelectCount + "个", 
                    type:"err",
                    timeout:Core.CONFIG.MsgTimeout
                });
                return;
            }
            if(arr.length){
                for(var i = 0; i < arr.length; i++){
                    var item = arr[i].split("*");
                    if(item.length == 2){
                        var key = new Date().getTime() + "_" + i;
                        _event.SelectFiles(key,item[0],item[1]);
                    }
                }
            }
        }

        var startLinten = function(){
            if(_TCache.ListenTimer){
                window.clearTimeout(_TCache.ListenTimer);
            }
            _TCache.ListenTimer = window.setTimeout(function(){
                var selectStr = _TCache.Uploader.GetFileList();
                if(selectStr != "NULL"){
                    Core.Debug.write(selectStr);
                    _TCache.Uploader.DeleteFileList();
                    selectFilesCallback(selectStr);
                }
                //监听事件
                for(var k in _UpList){
                    var file = _UpList[k];
                    var str = _TCache.Uploader.GetTaskInfo(Number(file.up_id));
                    _event.OnReFlashTaskInfo(file,str);
                }
                startLinten();
            },Core.CONFIG.TUpRefashFreq);
        }
		
        return {
            isInit: function(){
                return _TCache.initState;
            },
            select: function(){
                if(!_TCache.errorState){
                    return select();
                }
            },
            showDownload: function(){
                showDownload();
            },
            //通过PickCode续传文件
            reuploadByPickCode: function(pick_code){
                //判断是否安装上传控件
                if(_TCache.errorState){
                    showDownload();
                    return;
                }
                var file;
                for(var k in _UpList){
                    var item = _UpList[k];
                    if(item.pick_code == pick_code){
                        file = item;
                        break;
                    }
                }
                if(file){
                    if(_TUpload.reupload(file)){
                        Core.Debug.write("继传 file:" + file.up_id);
                        _DisplayForm.HideCTLButton(file,false,true);
                        _DisplayForm.ShowMessage(file.id,"准备继传...",0);
                    }
                    else{
                        Core.MinMessage.Show({
                            text:"续传文件失败", 
                            type:"err", 
                            timeout:Core.CONFIG.MsgTimeout
                        });
                    }
                }
                else{
                    Core.MinMessage.Show({
                        text:"本地缓存文件已删除,请重新选择", 
                        type:"err",
                        timeout:Core.CONFIG.MsgTimeout
                    });
                }
                _DisplayForm.Open();
            },
            delByPickCode: function(pick_code){
                var file;
                for(var k in _UpList){
                    var item = _UpList[k];
                    if(item.pick_code == pick_code){
                        file = item;
                        break;
                    }
                }
                if(file){
                    _DisplayForm.Del(file);
                    _TUpload.del(file);
                }
            },
            //暂停函数
            pause: function(file){
                var result = true;
                try{
                    _TCache.Uploader.StopUpTask(file.up_id);
                    return result;
                }
                catch(e){
                    Core.MinMessage.Show({
                        text:"暂停失败", 
                        type:"err", 
                        timeout: Core.CONFIG.MsgTimeout
                    });
                    Core.Debug.write("暂停失败");
                    return false;
                }
            },
            reupload: function(file){
                //续传
                var result = true;
                try{
                    _TCache.Uploader.ContinueUpTask(file.up_id);
                }
                catch(e){
                    Core.Debug.write("客户端上传出错");
                    result = false;
                }
                return result;
            },
            //删除函数
            del: function(file){
                var result = true;
                if(file.up_id){
                    //删除OCX列表
                    try{
                        if(_UpList[file.id]){
                            state = _TCache.Uploader.DeleteUpTask(file.up_id);
                            //state = _TCache.Uploader.DeleteUpTask(file.up_id,"user_id={user_id}&pick_code={pick_code}&rsa={rsa}");
                            Core.Debug.write("删除 up_id: " + file.up_id + " 状态: " + state);
                        }
						
                    }catch(e){
                        Core.Debug.write("客户端上传出错");
                        result = false;
                    }
                }
                if(result){
                    //删除数据
                    if(_UpList[file.id]){
                        _UpList[file.id] = null;
                        delete _UpList[file.id];
                        Core.SpaceData.Sync();
                    }
                }
                return result;
            },
            setDisabled: function(r){
                if(r){
                    $("#" + _TCache.UP_ID).addClass(_TCache.disable);
                }
                else{
                    $("#" + _TCache.UP_ID).removeClass(_TCache.disable);
                }
            },
            bindButton: function(id){
                _TCache.UP_ID = id;
            },
            show: function(txt){
                $("#" + _TCache.UP_ID).html(txt).show();
            },
            hide: function(){
                $("#" + _TCache.UP_ID).hide();
            },
            setting: function(aid,cid){
                if(aid == undefined){
                    aid = 1;
                    cid = 0;
                }
                if(cid.toString().indexOf("_0") != -1){
                    cid = 0;
                }
                var config = _cache.config[aid.toString()];
                _TCache.aid = aid;
                _TCache.cid = cid;
                try{
                    init(config);
                }catch(e){}
            },
            write: function(){
                if($.browser.msie){
                    if(!document.getElementById(Core.CONFIG.TUpDomId)){
                        var object = $('<object classid="' + Core.CONFIG.TUpClassID_NB + '" id="' + Core.CONFIG.TUpDomId + '" onreadystatechange="Core.Upload.TUpLoadStateChange(this);" style="position:absolute; top:-99999px;" onerror="Core.Upload.TUpLoadError();"></object>');
                        $(document.body).append(object);
                    }
                }
                else{ 
                    if(Core.CONFIG.IsWindows){
                        if (navigator.plugins && navigator.plugins.length > 0) {
							
                            var p = navigator.plugins["115.COM Upload Plugin"];
                            if (p) {
                                var object = $('<embed id="' + Core.CONFIG.TUpDomId + '" type="application/ylmf-upload" width="0" height="0" style="position:absolute; top:-99999px;" />');
                                $(document.body).append(object);
                            }else{
                                Core.Upload.TUpLoadError();
                            }
                        }
                        else{
                            Core.Upload.TUpLoadError();
                        }
                    }
                    else{
                        Core.Upload.TUpLoadError();
                    }
                }
                
                $(document).bind("keyup", function(e){
                    if(e.ctrlKey && e.shiftKey && e.keyCode == 220){
                        Core.CONFIG.TUpDebugTime++;
                        if(Core.CONFIG.TUpDebugTime > 5){
                            if(!Core.CONFIG.TUpDebugKey){
                                Core.CONFIG.TUpDebugKey = true;
                                
                                Core.MinMessage.Show({text: "断点续传调试已开启", type: "suc", timeout: 2000});
                            }
                        }
                    }
                })
            },
            statechange: function(ele){
            },
            loaderror: function(){
                _TCache.errorState = true;
                if(document.getElementById(Core.CONFIG.TUpDomId)){
                    document.body.removeChild(document.getElementById(Core.CONFIG.TUpDomId));
                }
            },
            isStart: function(){
                return _TCache.initState;
            },
            isInstall: function(){
                return !_TCache.errorState;
            }
        }
    })();
	
    //普通上传
    var _FUpload = (function(){
        var _FCache = {
            initState: false
        }
		
        var _dataAccess = {
            del: function(file){
                if(_FCache.Uploader.getFile(file.id)){
                    _FCache.Uploader.cancelUpload(file.id);
                }
                _DisplayForm.Del(file);
            }
        }
		
        var fBindEvents = function(settings){
            settings.swfupload_loaded_handler = function(){
                if(!_FCache.loaded){
                    _FCache.loaded = true;
                    if(_loadedFunList){
                        for(var i = 0, len = _loadedFunList.length; i < len; i++){
                            _loadedFunList[i]();
                        }
                        _loadedFunList = false;
                    }
                    if(_FloadedCallback){
                        _FloadedCallback();
                    }
                }
            }
			
            //用户上传
            settings.file_queued_handler = function(file){
                //文件选择对话框关闭消失事件,一次选择了多个文件，会执行多次这个事件
                file.up_type = 0;
                file.aid = this.customSettings.aid;
                file.cid = this.customSettings.cid;
				
				
                //文件大小与空间大小限制过滤
                if(!_DisplayForm.IsExist(file)){
                    //判断文件名
                    if(Util.Validate.mb_strlen(file.name) > 451){
                        _FCache.Uploader.cancelUpload(file.id);
                        file.error = "文件名过长";
                    }
                    else{
                        //判断空间使用大小
                        if(!this.customSettings.FileSizeTotal){
                            this.customSettings.FileSizeTotal = {};
                            var spaceData = Core.SpaceData.GetData();
                            for(var k in spaceData){
                                if(!this.customSettings.FileSizeTotal[k]){
                                    this.customSettings.FileSizeTotal[k] = {};
                                }
                                this.customSettings.FileSizeTotal[k].used  = Number(spaceData[k].used);
                                this.customSettings.FileSizeTotal[k].total = Number(spaceData[k].total);
                            }
                        }
                        var spaceKey = this.customSettings.aid;
                        if(Number(spaceKey) > 0 && Number(spaceKey) != 5){
                            spaceKey = 1;
                        }
                        var useSizeItem = this.customSettings.FileSizeTotal[spaceKey.toString()];
                        if(useSizeItem){
                            if((Number(useSizeItem.used) + Number(file.size)) > Number(useSizeItem.total)){
                                //空间不足
                                _FCache.Uploader.cancelUpload(file.id);
                                file.error = "空间不足";
                                _DisplayForm.Add(file);
                                _DisplayForm.Open();
                                return;
                            }						
                            useSizeItem.used = Number(useSizeItem.used) + Number(file.size);
                        }
                    }
                    file.complete = 0;
                    _DisplayForm.Add(file);
                    
                    file.is_uploading = 1;
                    _DisplayForm.Open();
                }
                else{
                    _FCache.Uploader.cancelUpload(file.id);
                }
            }
	
            settings.file_queue_error_handler=function(file,error,message){
                //选择的文件加入到上传队列中失败事件
                if(_cacheConfig.upload_size_limit > file.size && error == "-110"){
                    file.error = "请改用极速上传, 普通上传不支持上传大于1G的文件";
                }
                else{
                    file.error = String.format(Core.CONFIG.FUpErrMsg[error],Util.File.ShowSize(Number(_cacheConfig.upload_size_limit)));
                }
                _DisplayForm.Add(file);
                _DisplayForm.Open();
            }
	
            settings.file_dialog_complete_handler=function(selected,queued){
                //选择文件对话框关闭时事件 selected是选择的文件数目queued是此次选择的文件中成功加入队列的文件数目
                if(!_FCache.Uploader.getFile()){
                    this.customSettings.FileSizeTotal = null;
                }
                this.startUpload();
            }
	
            settings.upload_start_handler=function(file){
                //在文件往服务端上传之前触发此事件
                file = _DisplayForm.Get(file.id);
                _FCache.isupload = true;
                _FUpload.setting(file.aid, file.cid);
                _FCache.isupload = false;
                _DisplayForm.Progress(file);
                this.customSettings.StartTime = new Date();
                
            }
	
            settings.upload_progress_handler=function(file,c,t){
                //上传中定时事件；参数分别的上传文件对象、已上传的字节数、总共的字节数
                file = _DisplayForm.Get(file.id);
                if(file){
                    file.complete = c;
                    file.total = t;
                    var useTime =  new Date().getTime() - this.customSettings.StartTime.getTime();
                    var speed = Number(c / useTime );	//速度 byte/毫秒
					
                    var speedstr = (speed * 1000 / 1024);
                    if(speedstr > 1024){
                        speedstr = (speedstr/1204).toFixed(1) + 'm';
                    }
                    else{
                        speedstr = speedstr.toFixed(1) + 'k';
                    }
					
                    var pro = (c / t) * 100;
                    if(pro > 99){
                        pro = 99;
                    }
                    file.progress = pro.toFixed(1) + "%";
                    file.speed = speed;
                    file.speed_str = "("+speedstr+"/s)";
                    _DisplayForm.Progress(file);
                }
            }
	
            settings.upload_error_handler= function(file,error,message){
                //上传被终止或者没有成功完成触发的事件
                file = _DisplayForm.Get(file.id);
                if(file){
                    file.is_uploading = 0;
                    this.customSettings.UploadFileSize -= file.size;
                    this.customSettings.TotalSize -= file.size;
                    file.error = Core.CONFIG.FUpErrMsg[error];
                    _DisplayForm.Error(file);
                }
            }
	
            settings.upload_success_handler = function(file,data){ 
                //上传单个成功事件
                file = _DisplayForm.Get(file.id);
                file.is_uploading = 0;
                try{
                    Core.Debug.write(data);
                    data = eval("("+data+")");
                    if(data.state){
                        try{
                            //if(Core.FileConfig.DataAPI) Core.FileConfig.DataAPI.AddOne(data.data); 
                            _DisplayForm.ReloadPage(data.aid, data.cid);
                        }catch(e){}
                        _DisplayForm.Success(file);
                        //同步空间数据
                        Core.SpaceData.ChangeUse(data.aid,file.size,1);
                        this.customSettings.UploadFileSize -= file.size;
                        this.customSettings.CompleteSize += file.size;
                        return;
                    }
                    file.error = data.message;
                }
                catch(e){
                    file.error = "错误: 未知原因";
                }
                _DisplayForm.Error(file);
            }
	
            settings.upload_complete_handler = function(file){
                //上传单个完成事件
                file = _DisplayForm.Get(file.id);
                file && (file.is_uploading = 0);
            }
	
            settings.queue_complete_handler = function(){
            //上传列队完成事件
            }
        }
		
        //设置Flash配置
        var setting = function(data){
            var typeStr = data.upload_type_limit == "*"? "*.*" : ("*." + data.upload_type_limit.join(";*."));
            var params;
            if(data.cid){
                if(data.cid.toString().indexOf("_0") != -1){
                    data.cid = 0;
                }
                params = {
            		SESSIONID: data.session_id,
                    aid:data.aid,
                    cid:data.cid,
                    cookie:USER_COOKIE
                };
            }
            else{
                params = {
            		SESSIONID: data.session_id,
                    aid:data.aid,
                    cookie:USER_COOKIE
                };
            }
            //try{
            if(!_FCache.Uploader){
                var settings = {
                    flash_url: Core.CONFIG.FUpSWF,
                    upload_url: data.upload_url,
                    file_types_description: typeStr,
                    file_upload_limit: 0,
                    file_types: typeStr,
                    file_size_limit: Util.File.ShowSize(data.upload_size_limit),
                    file_queue_limit: 0,
                    button_action : SWFUpload.BUTTON_ACTION.SELECT_FILES,
                    custom_settings: {
                        aid:data.aid,
                        cid:data.cid
                    },
                    debug: Core.CONFIG.FUpDebug,
                    post_params: params,
                    button_cursor : SWFUpload.CURSOR.HAND,
                    button_image_url: Core.CONFIG.FUpImg ,
                    button_width: "100",
                    button_height: "30",
                    button_placeholder_id: _FCache.UP_ID,
                    button_window_mode : SWFUpload.WINDOW_MODE.TRANSPARENT
                };
                fBindEvents(settings);
                if(SWFUpload){
                    _FCache.Uploader = new SWFUpload(settings);
                }
            }
            else{
				
                if(!_FCache.isupload){
                    /***改变上传配置***/
                    // 上传文件描述 上传文件类型
                    if(!_FCache.loaded){
                        _loadedFunList.push(function(){
                            setting(data);
                        });
                        return;
                    }
                    _FCache.Uploader.setFileTypes(typeStr,typeStr);
                    // 更新 大小限制
                    _FCache.Uploader.setFileSizeLimit(Util.File.ShowSize(data.upload_size_limit));
                    _FCache.Uploader.customSettings.aid = data.aid;
                    _FCache.Uploader.customSettings.cid = data.cid;
                }
                else{
                    _FCache.Uploader.setUploadURL(data.upload_url);
                    if(data.cid){
                        _FCache.Uploader.setPostParams({
                        	SESSIONID: data.session_id,
                            aid:data.aid,
                            cid:data.cid,
                            cookie:USER_COOKIE
                        });
                    }
                    else{
                        _FCache.Uploader.setPostParams({
                        	SESSIONID: data.session_id,
                            aid:data.aid,
                            cookie:USER_COOKIE
                        });
                    }
					
                }
            }
        //}catch(e){}
        }
		
        var _cacheConfig;
        var init = function(config){
            _cacheConfig = config;
            if(!_FCache.initState){
                //初始化
                //1 动态加载JS
                
                Util.Load.JS(Core.CONFIG.JSPath.FUp, function(){
                    window.setTimeout(function(){
                        _FCache.initState = true;
                        setting(_cacheConfig);
                    }, 10);
                });
            }
            else{
                setting(_cacheConfig);
            }
        }
		
        var _loadedFunList = [];
        return {
            isStart:function(){
                return _FCache.loaded;
            },
            getAccess: function(){
                return _dataAccess;
            },
            dom: function(id,boxId){
                _FCache.UP_ID = id;
                _FCache.Box_ID = boxId;
            },
            show: function(){
                $("#" + _FCache.Box_ID).css({
                    top:"",
                    position:""
                });
            },
            hide: function(){
                $("#" + _FCache.Box_ID).css({
                    top:-9999 + "px",
                    position: "absolute"
                });
            },
            setting: function(aid,cid){
                if(aid == undefined){
                    aid = 1;
                    cid = 0;
                }
                var config = _cache.config[aid.toString()];
                
                config.cid = cid;
                init(config);
            },
            setDisabled: function(disable){
                if(!_FCache.loaded){
                    _loadedFunList.push(function(){
                        _FCache.Uploader.setButtonDisabled(disable);
                    });
                    return;
                }
                if(_FCache.Uploader){
                    _FCache.Uploader.setButtonDisabled(disable);
                }
            }
        }
    })();
	
    var _UpCTL = (function(){
        var _btn;
		
        return {
            show: function(){
                _btn.show();
            },
            hide: function(){
                _btn.hide();
            },
            setting: function(aid,cid){
                if(_FUpload.isStart()){
                    _FUpload.setting(aid, cid);
                }
                if(_TUpload.isStart()){
                    _TUpload.setting(aid, cid);
                }
                _DisplayForm.ChangeDir(aid, cid);
            },
            setDisabled: function(disable){
                _FUpload.setDisabled(disable);
                _TUpload.setDisabled(disable);
            }
        }
    })();
	
    var _FloadedCallback;
	
    return {
        GetTUploadInstall: function(){
            return _TUpload.isInstall();
        },
        ShowOCXDownLoad: function(){
            _TUpload.showDownload();
        },
        Show: function(aid, cid, notSelect){
            Core.Tree.CheckIsLoad(function(){
                Core.Upload.SetCatalog(aid, cid);
                Core.Upload.Open(notSelect);
            });
        },
        Open: function(notSelect){
            var doClose = _DisplayForm.IsClose();
            _DisplayForm.Open();
            if(!notSelect && Core.CONFIG.UpEngine != 0 && _TUpload.isInstall()){
                //doClose && _DisplayForm.Close();
                window.setTimeout(function(){
                    if(_TUpload.select() === -1){
                        _DisplayForm.Open();
                    }
                },10);
                return;
            }
            
        },
        WriteOCX: function(){
            _TUpload.write();
        },
        //改变上传目录
        SetCatalog: function(aid,cid){
            _cache.ActiveAid = aid;
            _cache.ActiveCid = cid;
            _UpCTL.setting(_cache.ActiveAid,_cache.ActiveCid);
            
        },
        SetConfig: function(config){
            _cache.config = config;			
        },
        //改变上传引擎
        ChangeEngine: function(engine){
            Core.CONFIG.UpEngine = engine;
            _UpCTL.setting(_cache.ActiveAid,_cache.ActiveCid);
            _DisplayForm.Install();
        },
        //安装OCX控件出错状态显示
        TUpLoadError: function(){
            _TUpload.loaderror();
        },
        //安装OCX控件出错状态显示
        TUpLoadStateChange: function(ele){
            _TUpload.statechange(ele);
        },
        Disable: function(r){
            _UpCTL.setDisabled(r);
        },
        ReuploadByPickCode: function(pick_code){
            if(_TUpload.isInit()){
                for(var i = 0, len = pick_code.length; i < len; i++){
                    var item = pick_code[i]
                    _TUpload.reuploadByPickCode(item);
                }
            }
            else{
                _TUpload.initCallback = function(){
                    window.setTimeout(function(){
                        for(var i = 0, len = pick_code.length; i < len; i++){
                            var item = pick_code[i]
                            _TUpload.reuploadByPickCode(item);
                        }
                    },20);
                }
                Core.Upload.Show(1, 0, true);
                //Core.Upload.Open(true);
            }
        },
        DeleteByPickCode: function(pick_code){
            _TUpload.delByPickCode(pick_code);
        },
        CheckUpEngine: function(){
            _DisplayForm.CheckUpEngine();
        }
    }
})();

/*
	音乐播放器
*/
Core.MusicPlayer = (function(){
    var _win = function(){
        var _content = $('<div class="player-wrap" rel="play_title">'+
                                '<div class="title-handle">'+
                                    '<a href="javascript:;" class="ha-minimize" btn="min">最小化</a>'+
                                    '<a href="javascript:;" class="ha-maximize" btn="max" style="display:none;">最大化</a>'+
                                    '<a href="javascript:;" class="ha-close" btn="close">关闭</a>'+
                                '</div>'+
                                '<div class="player-ctrl">'+
                                    '<a href="javascript:;" class="play" jplay="play">播放</a>'+
                                    '<a href="javascript:;" class="pause" style="display:none;" jplay="pause">暂停</a>'+
                                '</div>'+
                                '<div class="player-song" rel="play_name"></div>'+
                                '<div class="player-pannel">'+
                                    '<a href="javascript:;" class="player-prev" jplay="per">上一曲</a>'+
                                    '<a href="javascript:;" class="player-stop" jplay="stop">停止</a>'+
                                    '<a href="javascript:;" class="player-next" jplay="next">下一曲</a>'+
                                    '<a href="javascript:;" class="loop-single" jplay="mode_1" title="单曲循环">单曲循环</a>'+
                                    '<a href="javascript:;" class="loop-list" jplay="mode_2" title="列表循环">列表循环</a>'+
                                    '<a href="javascript:;" class="loop-random" jplay="mode_0" title="随机播放">随机播放</a>'+
                                    '<a href="javascript:;" class="player-mute" jplay="volume_open">声音</a>'+
                                    '<a href="javascript:;" class="player-volume" jplay="volume_close" style="display:none;">静音</a>'+
                                '</div>'+
                                '<div class="progress-bar volume-bar" jplay="volume_line">'+
                                    '<div class="bar-con" jplay="volume_size_line"><b jplay="volume_button"></b></div>'+
                                '</div>'+
                            '</div>'+
                            '<div class="player-progress">'+
                                '<div class="progress-bar" jplay="progress_line">'+
                                    '<div class="download-bar" style="width:0;"  jplay="download_line"><i></i></div>'+
                                    '<div class="bar-con" style="width:0;" jplay="play_line"><b></b></div>'+
                                '</div>'+
                                '<div class="progress-num"><span jplay="play_time"></span>/<span jplay="total_time"></span></div>'+
                            '</div>'+
                            '<div class="music-box" rel="list_box">'+
                                '<dl class="file-list" rel="list"></dl>'+
                            '</div>' +
                            '<div class="status-bar" rel="bottom">'+
                                '<div class="con">'+
                                    '<span rel="total"></span>'+
                                    '<div class="stat-menu">'+
                                        '<a href="javascript:;" btn="clear"><span><i class="icon ico-remove"></i><i>清空列表</i></span></a>'+
                                    '</div>'+
                                '</div>'+
                            '</div>');
		
        var _cache = {}, _self = this;
		
        Core.WindowBase.call(this,{
            content:_content,  
            min_title:'播放器', 
            is_not_title: true, 
            is_not_resize: true, 
            is_not_min_title: true
        });
        
        var createMinBox = function(){
            if(!_cache.minBox){
                _cache.minBox = $('<div class="player-min" style="display:none;z-index:99">'+
                                    '<div class="title-handle">'+
                                        '<a href="javascript:;" class="ha-maximize" btn="max">还原</a>'+
                                        '<a href="javascript:;" class="ha-close" btn="close">关闭</a>'+
                                    '</div>'+
                                    '<div class="player-pannel">'+
                                        '<a href="javascript:;" class="player-prev" jplay="per">上一曲</a>'+
                                        '<a href="javascript:;" class="player-play" jplay="play">播放</a>'+
                                        '<a href="javascript:;" class="player-pause" jplay="pause">暂停</a>'+
                                        '<a href="javascript:;" class="player-next" jplay="next">下一曲</a>'+
                                    '</div>');
                $(document.body).append(_cache.minBox);
                _cache.minBox.find("[btn]").bind("click", function(){
                    switch($(this).attr("btn")){
                        case "max":
                            _self.warp.find("[btn='max']").hide();
                            _self.warp.find("[btn='min']").show();
                            _self.warp.addClass("music-player").removeClass("min-player");
                            _self.warp.css({
                                height:""
                            });
                            openFun();
                            hideMinBox();
                            break;
                        
                        case "close":
                            _self.Close();
                            break;
                    }
                })
            }
        }
        
        var maxMinBox = function(){
            createMinBox();
            _cache.minBox.show();
        }
        
        var hideMinBox = function(){
            if(_cache.minBox){
                _cache.minBox.hide();
            }
        }

        this.Initial = function(){
            if(!_cache.initState){
                _self.warp.addClass("music-player");
                createMinBox();
                jPlayerProxy.Bind($(Core.CONFIG.MusicPlay),[_content, _cache.minBox]);
	
                jPlayerProxy.Action = {
                    //开始播放回调 obj音乐对象 是添加音乐时传进去的对象,对象会多了一个Key的字段是唯一标示
                    StartPlay: function(obj){
                        var dom = _content.find("[rel='list']");
                        if(_cache.old_odd){
                            _cache.old_odd.removeClass("playing");
                            _cache.old_odd = false;
                        }
                        _content.find('[rel="play_name"]').html(obj.name);
                        _cache.old_odd = dom.find('[key="'+obj.key+'"]')
                        _cache.old_odd.addClass("playing");
						
                    },
                    //添加音乐回调  参数arr: 添加成功的列表[array] 数组项里是添加音乐时传进去的对象每个对象会多了一个Key的字段是唯一标示
                    AddMusic: function(arr){
                        var dom = _content.find("[rel='list']");
                        var isPlay = !dom.find("dd[key]").length; 
                        var firstItem = false;
                        
                        var list = [];
                        
                        for(var i = 0, len = arr.length; i < len; i++){
                            var item = arr[i];
                            if(!firstItem){
                                firstItem = item;
                            }
                            var ele = $(String.formatmodel('<dd key="{key}" style="display:none;"><ul><li class="file-name"><i class="icon ico-play"></i><a href="javascript:;" btn="play">{name}</a></li><li class="file-operate"><a href="{mp3}" target="_blank" class="opt-icon opt-download">下载</a> <a href="javascript:;" class="opt-icon opt-delete" btn="del">删除</a></li></ul></dd>', item));
                            ele.find("[btn]").bind("click",{
                                mod: item
                            },function(e){
                                switch($(this).attr("btn")){
                                    case "play":
                                        jPlayerProxy.Play(e.data.mod.key);
                                        break;
                                    case "del":
                                        jPlayerProxy.Delete(e.data.mod.key);
                                        break;
                                }
                                return false;
                            })
                            dom.append(ele);
                            list.push(ele);
                        }
                        for(var i = 0, len = list.length; i < len; i++){
                            list[i].fadeIn("slow");
                        }
                        window.setTimeout(function(){
                            dom.parent().scrollTop(dom.height());
                        }, 10);
                        if(isPlay && firstItem){
                            jPlayerProxy.Play(firstItem.key);
                        }
                    },
                    //删除音乐回调 参数key: 音乐列表的唯一标示
                    DeleteMusic: function(key){
                        var dom = _content.find("[rel='list']");
                        dom.find('[key="'+key+'"]').empty().remove();
                    },
                    //设置播放模式回调 disableBtns:关闭模式按钮[array]  enableBtns:启用模式的按钮[array]
                    SetMode: function(mod){
                        //下面是测试代码
                        _content.find("[jplay='mode_0']").hide();
                        _content.find("[jplay='mode_1']").hide();
                        _content.find("[jplay='mode_2']").hide();
                        switch(mod){
                            case 0:
                                _content.find("[jplay='mode_1']").show();
                                break;
                            case 1:
                                _content.find("[jplay='mode_2']").show();
                                break;
                            case 2:
                                _content.find("[jplay='mode_0']").show();
                                break;
                        }
                    }
                }
                jPlayerProxy.Action.SetMode(1);
				
                _content.find("[rel='list']").mousedown(function(e){
                    Core.Html.StopPropagation(e);
                });
                _self.warp.find("[rel='list_box']").mousedown(function(e){
                    Core.Html.StopPropagation(e);
                });
                
                _content.find("[btn]").mousedown(function(e){
                    Core.Html.StopPropagation(e);
                    switch($(this).attr("btn")){
                        case "min":
                            //最小化
                            maxMinBox();
                            _self.Hide();
                            break;
                        case "close":
                            _self.Close();
                            break;
                    }
                })
				
                _cache.initState = true;
            }
            _self.warp.find("[btn='clear']").click(function(){
                clear();
                return false;
            })
        }
		
        var clear = function(){
            var dom = _content.find("[rel='list']");
            dom.find("dd[key]").each(function(){
                jPlayerProxy.Delete($(this).attr("key"));
            })
			
        }
				
        var openFun = _self.Open;
		
        //打开窗体
        this.Open = function(arr, isplay){
            openFun();
            jPlayerProxy.Add(arr, isplay);
        }
		
        var closeFun = _self.Close;
        this.Close = function(){
            jPlayerProxy.Stop();
            hideMinBox();
            clear();
            closeFun();
        }
    }
	
    var _isLoading = false, _model;
	
    return {
        Add: function(arr, isplay){
            if(!_model){
                //加载JS
                if(_isLoading) return;
                _isLoading = true;
                Util.Load.Css(Core.CONFIG.CssPath.Play);
                Util.Load.JS(Core.CONFIG.JSPath.JPlayer, function(){
                    Util.Load.JS(Core.CONFIG.JSPath.JPProxy, function(){
                        _isLoading = false;
                        _model = new _win();
                        _model.Open(arr, isplay);
                    })
                });
            }
            else{
                _model.Open(arr, isplay);
            }
        }
    }
})()


/*图片浏览器使用的JS接口*/
var IB = (function(){
    return {
        close:function(msg){
            Core.PhotoView.Hide();
        },
        isready:function(){
            window.setTimeout(function(){
                Core.MinMessage.Hide();
                Core.PhotoView.Open(function(){
                    window.setTimeout(function(){
                        var flash = document.getElementById('js_flash_main');
                        flash.focus(); 
                    }, 10);
                });  
                  
            },10);
        },
        XML: "",
        download: function(url){
            if(url){
                if(url.indexOf('u=vip%7C') != -1){
                    url = url.replace('u=vip%7C', "u=vip|");
                }
                if($.browser.msie){
                    var params = url.replace(/^.*\?/, "");
                    var action = url.replace(/\?.*$/, "");
                    var arr = params.split("&");

                    var form = document.createElement("form");
                    form.action = action;
                    form.target = "_blank";
                    form.method = "get";
                    document.body.appendChild(form);
                    for(var i = 0, len = arr.length; i < len; i++){
                        var item = arr[i].split("=");
                        if(item && item.length == 2){
                            var input = document.createElement('input');
                            input.type = "hidden";
                            input.name = item[0];
                            input.value = item[1];
                            form.appendChild(input);
                        }
                    }
                    form.submit();
                    window.setTimeout(function(){
                        document.body.removeChild(form);
                    }, 30);
                }
                else{
                    window.open(url);
                }
            }
            else{
                alert("下载链接不存在，请联系客服")
            }
        }
    }
})();

/*图片浏览器*/
Core.PhotoView = (function(){
    var _dom, _is_bind_resize = false, _resizeTimer;
	
    var openFlash = function(callback){
        
        if(!_dom){
            Core.MinMessage.Show({
                text: "正加载图片浏览器...", 
                type:"load"
            });
            var url = Core.CONFIG.SWFPath.PhotoView;
            
            var html = [];
            if($.browser.msie){
                html.push('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="100%" height="100%" name="js_flash_main" id="js_flash_main">');
                html.push('<param name="movie" value="' + url + "?" + new Date().getTime() + '" />');
                html.push('<param name="quality" value="high" />');
                html.push('<param name="allowScriptAccess" value="sameDomain" />');
                html.push('<param name="allowFullScreen" value="true" />');
                html.push('<param name="wmode" value="transparent" />');
                html.push('<param name="flashvars" value="callback=IB.isready&closefn=IB.close&download=IB.download&loading='+Core.CONFIG.SWFPath.SWF_LoadImg+'&xml='+encodeURIComponent(IB.XML)+'" />');
                html.push('</object>');
            }
            else{
                html.push('<object type="application/x-shockwave-flash" data="' + url + "?009" + '" width="100%" height="100%" id="js_flash_main">');
                html.push('<param name="quality" value="high" />');
                html.push('<param name="allowScriptAccess" value="sameDomain" />');
                html.push('<param name="allowFullScreen" value="true" />');
                html.push('<param name="wmode" value="transparent" />');
                html.push('<param name="flashvars" value="callback=IB.isready&closefn=IB.close&download=IB.download&loading='+Core.CONFIG.SWFPath.SWF_LoadImg+'&xml='+encodeURIComponent(IB.XML)+'" />');
                html.push('</object>');
                
            }
            
            _dom = $('<div style="position:absolute;height:100%; width:100%;top:-99999px;z-index:999999999;overflow:hidden;"><div style="position:absolute;height:100%; width:100%;top:0;left:0;right:0;bottom:0;filter:alpha(opacity=80);opacity:0.8;background:#000;z-index:9999999998;"></div> <div style="position:absolute;height:100%; width:100%; z-index:9999999999;" rel="flash"></div></div>');
            
            $(document.body).append(_dom);
            window.setTimeout(function(){
                _dom.find("[rel='flash']").html(html.join(""));
            }, 30);
            
            if($.browser.msie && $.browser.version == 6){
                window.setTimeout(function(){
                    _dom.height(_dom.height() + 40);
                }, 10);
                if(!_is_bind_resize){
                    _is_bind_resize = true;
                    $(window).bind("resize", function(){
                        
                        if(_dom){
                            if(_resizeTimer){
                                window.clearTimeout(_resizeTimer);
                            }
                            _dom.css("height", "100%");
                            _resizeTimer = window.setTimeout(function(){
                                _dom.height(_dom.height() + 40);
                            }, 10);
                        }
                    })
                }
            }
        }
    }
	
    return {
        Show: function(aid, cid, tid, is_online, start, limit, ids){
            
            //
            // 针对地理信息归类判断
            //
            if (aid == 3) {
                IB.XML = PAGE_PATHS["MY"] + "/index.php?r=operate/index&ct=app&ac=get_online_img&aid="+aid+"&cid="+cid+"&tid=" + tid + "&s=" + start + "&limit=" + limit + "&_t=" + new Date().getTime();
            } else {
                IB.XML = PAGE_PATHS["MY"] + "/index.php?r=operate/index&ct=app&ac=get_online_img&aid="+aid+"&cid="+cid+"&tid=" + tid + "&s=" + start + "&limit=" + limit + "&ids=" + ids + "&_t=" + new Date().getTime();
            }
            openFlash();
            return;
            
            if(is_online == "1"){
                IB.XML = PAGE_PATHS["MY"] + "/?ct=app&ac=get_online_img&aid="+aid+"&cid="+cid+"&tid=" + tid + "&_t=" + new Date().getTime();
                openFlash();
            }
            else{
                Core.MinMessage.Show({
                    text: "由于图片太大或网络的原因，暂不支持在线查看",
                    type: "war",
                    timeout: Core.CONFIG.MsgTimeout
                })
            }
        },
        Open: function(callback){
            if(_dom){
                _dom.css({
                    top: "0"
                });
            }
            callback && callback();
        },
        Hide: function(){
            if(_dom){
                _dom.find("[rel='flash']").children().empty().remove();
                
                _dom.css({
                    top: "-99999px"
                });

                _dom.html("");
                _dom.remove();
                _dom = false;
                
            }
        }
    }
})();

Core.Reader = (function(){
    
    var _mod = function(){
        var _self = this, _event, _cache = {};
        var _content = $('<div style="height:100%;position:absolute;left:0;top:0;width:100%;z-index:0;">'+
            '<div class="common-frame" rel="content"></div>'+
            '</div>');
        Core.WindowBase.call(this, {
            title:'<span>文档阅读器</span>',
            content: _content, 
            min_title:'<span>文档阅读器</span>', 
            width:950, 
            height: 500,
            min_width:900
        });
        
        
        var createAPI = function(){
            if(!window.SWFVIEW){
                window.SWFVIEW={
                    docReady: function(){
                        WS.Message.Hide();
                    },
                    ready:function(){
                        if(_event && _event.ready){
                            _event.ready();

                        }
                    },
                    error:function(code,msg){
                        if(_event && _event.error){
                            _event.error();
                        }
                        else{
                            alert("code:"+code+"    msg:"+msg);
                        }
                    },
                    onclik_help:function(){
                        if(_event && _event.help){
                            _event.help();
                        }
                        else{
                            alert("You click on the help button!");
                        }
                    },
                    esckeyup: function(){
                        if(_event && _event.esckeyup){
                            _event.esckeyup();
                        }
                    }
                }
            }
        }
        
        this.Initial = function(){
            createAPI();
        }
        
        var _openFun = _self.Open;
        var _closeFun = _self.Close;
        var _maxFun = _self.Max;
        var _maxState = false;
        
        this.Open = function(url){
            Core.MinMessage.Show({text: "文档加载中。。。", type: "load", timeout: 30000});
            _openFun();
            
            if(_maxState){
                _maxState = false;
                Core.MinMessage.Hide();
                return;
            }
            //初始化事件
           _event = {
               ready: function(){
                   Core.MinMessage.Hide();
               },
               error: function(){
                   //TODO: 展示加载Flash错误页面
               },
               help: function(){
                   //TODO: 打开帮助页面
               },
               esckeyup: function(){
                   _self.Close();
               }
           }
            
            var conBox = _content.find("[rel='content']");
            conBox.html("");
            
            var html = [];
            var swf_Url = Core.CONFIG.Reader.URL + "&swf=" + url;
            if($.browser.msie){
                html.push('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="100%" height="100%" id="'+Core.CONFIG.Reader.ID+'">');
                html.push('<param name="movie" value="' + swf_Url + '" />');
                html.push('<param name="quality" value="high" />');
                html.push('<param name="allowScriptAccess" value="always" />');
                html.push('<param name="allowFullScreen" value="true" />');
                html.push('<param name="wmode" value="opaque" />');
                html.push('</object>');
            }
            else{
                html.push('<object type="application/x-shockwave-flash" data="' + swf_Url + '" width="100%" height="100%" id="'+Core.CONFIG.Reader.ID+'">');
                html.push('<param name="quality" value="high" />');
                html.push('<param name="allowScriptAccess" value="allowDomain" />');
                html.push('<param name="allowFullScreen" value="true" />');

                html.push('<param name="wmode" value="opaque" />');


                html.push('</object>');
            }
            var box = $(html.join(""));
            conBox.append(box);
        }
        
        this.Max = function(){
            _maxState = true;
            _maxFun();
        }
        
        this.Close = function(){
            var conBox = _content.find("[rel='content']");
            conBox.html("");
            _closeFun();
        }
    }
    
    var _reader;
    var _urlList = {};
    return {
        Open: function(pick_code){
            if(!_urlList[pick_code]){
                Core.MinMessage.Show({text: "文档加载中。。。", type: "load", timeout: 30000});
                $.ajax({
                    url: "?ct=app&ac=get_online_doc&pick_code=" + pick_code,
                    type: "GET",
                    cache: false,
                    dataType: "json",
                    success: function(r){
                        if(r.state){
                            var read_url = r.url;
                            
                            if(read_url == ""){
                                Core.MinMessage.Show({text: "该文档正在转换中，请稍候阅读。。。", type: "load", timeout: 2000});
                            }
                            else{
                                _urlList[pick_code] = read_url;
                                if(!_reader){
                                    _reader = new _mod();
                                }
                                _reader.Open(_urlList[pick_code]);
                            }
                            
                        }
                        else{
                            if(r.msg_code == 700007){
                                Core.MinMessage.Hide();
                                Core.FileAPI.Download(pick_code);
                            }
                            else if(r.msg_code == 700005){
                                Core.MinMessage.Show({text: r.msg, type: "war", timeout: 2000});
                            }
                            else{
                                Core.MinMessage.Show({text: r.msg, type: "err", timeout: 2000});
                            }
                        }
                    }
                })
            }
            else{
                if(!_reader){
                    _reader = new _mod();
                }
                _reader.Open(_urlList[pick_code]);
            }
        }
    }
})();

Core.UDownFile = (function(){
    return {
        Set: function(arr){
            //<div id="js_download_list_box" style="display:none;"></div>
            if($.browser.msie){
                
                var box = $("#js_download_list_box");
                if(!arr){
                    if(box.length){
                        box.html("");
                    }
                    return false;
                }
                if(!box.length){
                    box = $('<div id="js_download_list_box" style="display:none;"></div>');
                    $(document.body).append(box);
                }
                box.html("");
                for(var i = 0, len = arr.length; i < len; i++){
                    var item = arr[i];
                    if(item.attr("file_type") == "1"){
                        box.append($('<input value="' + Core.CONFIG.Path.U + "file/" + item.attr("pick_code") + '" filename="' + item.find('[field="file_name"]').attr("title") + '" />'));
                    }
                }
            return true;
            }
            else{
                return false;
            }
        }
    }
})();

//修改上部进度条的进度
Core.SpaceTop = (function(){
    return {
        Modify: function(){
        	Core.SpaceData.AddClient("top_space", function(data){
                key = "1";
                if(key && data[key]){
                    var space = data[key];
                    if(space.total){
                        //同步更新上部进度信息    modify by sylar
                        var spaceBoxTop = $("#js_space_box_top");
                        var spaceTextTop = spaceBoxTop.find("[rel='space_text']");
                        var spaceLineTop = spaceBoxTop.find("[rel='space_line']");
                        
                        var persent = (space.used * 100 / space.total).toFixed(2)  + "%";
                        
                        if((space.used * 100 / space.total) > 85){
                        	spaceLineTop.addClass("red-status");
                        }else{
                        	spaceLineTop.removeClass("red-status");
                        }
                        spaceTextTop.text(Util.File.ShowSize(space.used) +"/" + Util.File.ShowSize(space.total));
                        spaceLineTop.css({width: persent});
                    }
                }
            })
        }
    }
})();

/**
 * 创建修改图片地理信息dialog
 */
Core.FileExifDG = (function(){
    var _mod;
    var _model = function(){
        var _self = this, _cache={};
        var _content = $('<div class="dialog-wrap popup-input">'+
                '<input type="text" class="text" rel="latitude" />'+
            '</div>'+
            '<div class="dialog-wrap popup-input">'+
            '<input type="text" class="text" rel="longitude" />'+
            '</div>'+
            '<div class="dialog-bottom">'+
                '<div class="fr">'+
                    '<a href="javascript:;" class="button" btn="confirm"><span class="btn-con">确定</span></a>'+
                    '<a href="javascript:;" class="button btn-gray" btn="cancel"><span class="btn-con">取消</span></a>'+
                '</div>'+
            '</div>');
            Core.DialogBase.call(this,{
            content: _content, 
            title: '创建地理信息'
            });
            
            var createFun = function(){
            var lat = $.trim(_content.find('[rel="latitude"]').val());
            var lon = $.trim(_content.find('[rel="longitude"]').val());
            if(lat == ""){
                 Core.MinMessage.Show({text: "请输入完整经纬信息", type: "war", timeout: Core.CONFIG.MsgTimeout, window:_self});
                _content.find('[rel="latitude"]').focus();
                return false;
                return;
            }
            if(lon == ""){
                Core.MinMessage.Show({text: "请输入完整经纬信息", type: "war", timeout: Core.CONFIG.MsgTimeout, window:_self});
               _content.find('[rel="longitude"]').focus();
               return false;
               return;
            }
            var data = {};
            data["tid"] = tid;
            data["is_exif"] = is_exif;
            data["gps"] = gps;
            data["version"] = version;
            // 文件描述修改AJAX
            $.ajax({
                url:PAGE_PATHS["MY"]+"/index.php?r=operate/index&ct=file&ac=edit",
                data:data,
                dataType: "json",
                type: "POST",
                success: function(r){
                    if(r.state){
                        Core.MinMessage.Show({
                            text: "重命名成功", 
                            type: "suc", 
                            timeout: Core.CONFIG.MsgTimeout, 
                            window: Core.CONFIG.FileWindow
                        });
                        if(Core.FileConfig.DataAPI) Core.FileConfig.DataAPI.UpdateFile({
                            file_id: data.file_id, 
                            file_name:data.file_name
                        });
                    }
                    else{
                        Core.MinMessage.Show({
                            text: r.msg, 
                            type: "err", 
                            timeout: Core.CONFIG.MsgTimeout, 
                            window: Core.CONFIG.FileWindow
                        });
                    }
                }
            })
            _self.Close();
            
        }
        
        this.Initial = function(){
            _content.find("[rel='file_name']").bind("keydown", function(e){
                if(e.keyCode == 13){
                    createFun();
                }
                else if(e.keyCode == 27){
                    _self.Close();
                }
            })

            _content.find("[btn]").bind("click", function(e){
                switch($(this).attr("btn")){
                    case "confirm":
                        createFun();
                        break;
                    case "cancel":
                        _self.Close();
                        break;
                }
                return false;
            })
        }
        
        this.SetValue = function(file_id, file_name){
            _cache.file_id = file_id;
            var title = file_name;
            if(title.indexOf(".") != -1){
                _cache.suffix = title.substring(title.lastIndexOf("."), title.length);
                title = title.substring(0, title.lastIndexOf("."));
            }
            else{
                _cache.suffix = "";
            }
            _content.find('[rel="file_name"]').val(title);
            window.setTimeout(function(){
                _content.find('[rel="file_name"]').select();
            },20);
        }
    }
    
    
    return {
        Show: function(file_id, file_name){
            if(!_mod){
                _mod = new _model();
            }
            
            _mod.Open(function(){
                _mod.SetValue(file_id, file_name);
            });
        }
    }
})();
